go timed task crontab

In Linux, you can edit the scheduled tasks through crontab -e or vi /etc/crontab. The difference is that only the root user can use the latter, and you can also specify the shell environment. It is not recommended to modify it. It is recommended to back up before modification. The former can be used by any user. After modification, there is no need to modify and restart automatically.

1 linux crontab timing task

# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed

2 golang crontab timed task

2.1 Installation and use

2.1.1 Installation

go get github.com/robfig/cron/[email protected]

2.1.2 Import

import "github.com/robfig/cron/v3"

2.2 Time Rules

2.2.1 Standard Time Rules

# .------------------second (0 - 59)
# | .---------------- minute (0 - 59)
# | | .------------- hour (0 - 23)
# | | | .---------- day of month (1 - 31)
# | | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun
# | | | | | |
# * * * * * * user-name command to be executed

Note: The minimum granularity supported by cron is minutes by default. To support the second level, it needs to be enabled by passing in cron.WithSeconds(). The cron time expression after enabling is different from the crontab time expression in Linux. 

package crontab
import "github.com/robfig/cron"

func CronExec() {
    spec := "*/2 * * * * ?" //每2s执行一次
    spec := "0 5 10 * * ?" //每天早上10:05:00执行一次
    spec := "* * 10 * * ?" //每天10点开始的一个小时一直在执行
    spec := "* 1-59/10 * * * ?" //每天1分到59分每10分钟执行一次

    c := cron.New()
    id,err := c.AddFunc(spec, func()) {
        crontab()
    }
    if err != nil {
        fmt.Sprintf("crontab exec error: %v with id: %v", err, id)
    }
    c.Start()
    return c

func crontab() {
    fmt.Sprint("crontab exec...")
}
package main 
import crontab

func main() {
    //执行任务代码
    xxx  
   
    go func() {
        CronExec()
    }()
}

The following table example is written when second-level support is enabled:

expression illustrate
* * * * * * Executed every second
0 */1 * * * * Execute every minute
0 0 */1 * * * run every hour
0 0 0 */1 * * 00:00Executed once a day
0 30 23 */1 * * 23:30Executed once a day
0 0 0 1 */1 * Executed on the first day of every month
0 30 21 * * 1 21:30Execute every Monday

 

2.2.2 Predefined Time Rules

For ease of use, cron predefines some time rules:

  • @yearly: It can also be written as @annually, which means 0 o'clock on the first day of each year. Equivalent to 0 0 1 1 *;
  • @monthly: Indicates 0 o'clock on the first day of each month. Equivalent to 0 0 1 * *;
  • @weekly: Indicates the 0 o'clock of the first day of the week, note that the first day is Sunday, that is, the 0 o'clock at the end of Saturday and the beginning of Sunday. Equivalent to 0 0 * * 0;
  • @daily: It can also be written as @midnight, which means 0:00 every day. Equivalent to 0 0 * * *;
  • @hourly: Indicates the start of every hour. Equivalent to 0 * * * *.
func main() {
  c := cron.New()

  c.AddFunc("@hourly", func() {
    fmt.Println("Every hour")
  })

  c.AddFunc("@daily", func() {
    fmt.Println("Every day on midnight")
  })

  c.AddFunc("@weekly", func() {
    fmt.Println("Every week")
  })

  c.Start()

  for {
    time.Sleep(time.Second)
  }
}

Note: Using a cron.New() timing task in this way, each method executed is executed sequentially, that is to say, it does not start executing at the same time.

2.2.3 Fixed time interval

cron supports fixed time intervals, the format is:

@every <duration>

The meaning is to trigger every duration. <duration> will call the time.ParseDuration() function to parse, so any format supported by ParseDuration is acceptable. For example 1h30m10s.

2.2.4 Time zone

By default, all times are based on the current time zone. Of course, we can also specify the time zone, there are two ways:

Add a CRON_TZ= + specific time zone in front of the time string. The format of the specific time zone is described in detail in the previous carbon article. The Tokyo time zone is Asia/Tokyo, and the New York time zone is America/New_York;
when creating a cron object, add a time zone option cron.WithLocation(location), where location is the time zone object loaded by time.LoadLocation(zone), and zone is the specific time zone format. Or call the SetLocation() method of the created cron object to set the time zone.
 

func main() {
  nyc, _ := time.LoadLocation("America/New_York")
  c := cron.New(cron.WithLocation(nyc))
  c.AddFunc("0 6 * * ?", func() {
    fmt.Println("Every 6 o'clock at New York")
  })

  c.AddFunc("CRON_TZ=Asia/Tokyo 0 6 * * ?", func() {
    fmt.Println("Every 6 o'clock at Tokyo")
  })

  c.Start()

  for {
    time.Sleep(time.Second)
  }
}

2.3 Common methods

2.3.1 New()

will create a new (blank) cron job instance based on local time

// 创建一个默认的cron对象
cron.New()

// 自定义解析器
cron.New(cron.WithSeconds())

// Seconds field, optional
cron.New(cron.WithParser(cron.NewParser(
    cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor,
)))

2.3.2 AddJob()

// 有两个参数,第一个参数可以是cron表达式或者预定义时间表,第二个Job
func (c *Cron) AddJob(spec string, cmd Job) (EntryID, error)
 
// Job是一个接口,有一个Run方法
type Job interface {
    Run()
}

2.3.3 AddFunc()

A callback function will be added to the scheduled task instance, and the callback function will be executed according to the specified schedule.

// 有两个参数,第一个参数可以是cron表达式或者预定义时间表,第二个传入一个函数,就是要执行的任务

// 会返回一个Id和error

// 会把传入的cmd func转成FuncJob。FuncJob实现了Job接口

func (c *Cron) AddFunc(spec string, cmd func()) (EntryID, error) {

    return c.AddJob(spec, FuncJob(cmd))

}

2.3.4 Start()

Call the start method to start the task.

Guess you like

Origin blog.csdn.net/ygq13572549874/article/details/131443719