gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/sync/task/task.go (about)

     1  // Package task provides an interface for distributed jobs
     2  package task
     3  
     4  import (
     5  	"context"
     6  	"fmt"
     7  	"time"
     8  )
     9  
    10  // Task represents a distributed task
    11  type Task interface {
    12  	// Run runs a command immediately until completion
    13  	Run(Command) error
    14  	// Status provides status of last execution
    15  	Status() string
    16  }
    17  
    18  // Command to be executed
    19  type Command struct {
    20  	Name string
    21  	Func func() error
    22  }
    23  
    24  // Schedule represents a time or interval at which a task should run
    25  type Schedule struct {
    26  	// When to start the schedule. Zero time means immediately
    27  	Time time.Time
    28  	// Non zero interval dictates an ongoing schedule
    29  	Interval time.Duration
    30  }
    31  
    32  type Options struct {
    33  	// Pool size for workers
    34  	Pool int
    35  	// Alternative options
    36  	Context context.Context
    37  }
    38  
    39  type Option func(o *Options)
    40  
    41  func (c Command) Execute() error {
    42  	return c.Func()
    43  }
    44  
    45  func (c Command) String() string {
    46  	return c.Name
    47  }
    48  
    49  func (s Schedule) Run() <-chan time.Time {
    50  	d := s.Time.Sub(time.Now())
    51  
    52  	ch := make(chan time.Time, 1)
    53  
    54  	go func() {
    55  		// wait for start time
    56  		<-time.After(d)
    57  
    58  		// zero interval
    59  		if s.Interval == time.Duration(0) {
    60  			ch <- time.Now()
    61  			close(ch)
    62  			return
    63  		}
    64  
    65  		// start ticker
    66  		ticker := time.NewTicker(s.Interval)
    67  		defer ticker.Stop()
    68  		for t := range ticker.C {
    69  			ch <- t
    70  		}
    71  	}()
    72  
    73  	return ch
    74  }
    75  
    76  func (s Schedule) String() string {
    77  	return fmt.Sprintf("%d-%d", s.Time.Unix(), s.Interval)
    78  }
    79  
    80  // WithPool sets the pool size for concurrent work
    81  func WithPool(i int) Option {
    82  	return func(o *Options) {
    83  		o.Pool = i
    84  	}
    85  }