当前位置:网站首页>Go corn timing task simple application

Go corn timing task simple application

2022-06-21 17:33:00 Muzi text_ Ah

When writing some services , We may need to execute some methods on a regular basis , At this time, you need to use the scheduled task ; So I learned recently corn, It is easy to use

Guide pack

go get -v -u github.com/robfig/cron # Third party pull 

A simple example

package main

import (
	"fmt"
	"github.com/robfig/cron"
	"log"
)

func main() {
    
	log.Println("starting...")

	c := cron.New()

	if err := c.AddFunc("*/1 * * * * *", example); err != nil {
    
		fmt.Println(err)
	}
	c.Start()
	select {
     // Query statement , Keep the program running , Here it is equivalent to for{}
	}
}

func example() {
    
	log.Println("Hello World!")
}

AddFunc The symbol after

//* * * * * *
//  first  second (0 - 60)
//  the second  min (0 - 59)
//  Third  hour (0 - 23)
//  The fourth one  day of month (1 - 31)
//  The fifth one  month (1 - 12)
//  Sixth  day of week (0 - 6) (0 to 6 are Sunday to Saturday)

Match symbols

// asterisk (*) : Express  cron  The expression can match all the values of the field . As in the 5 Use an asterisk for each field (month), It means every month 
// Oblique line (/): Represents the growth interval , As the first 2 A field (minutes)  The value is  3-59/15, Means the... Of every hour 3 Minutes to start , after   every other  15  Once per minute ( namely  3(3+0*15)、18(3+1*15)、33(3+2*15)、48(3+3*15)  At these points in time ), It can also be expressed here as :3/15
// comma (,): Used to enumerate values , As the first 6 The first field value is  MON,WED,FRI, Express   Monday 、 3、 ... and 、 5、 ... and   perform 
// hyphen (-): Represents a range , As the first 3 The value of the first field is  9-17  Express  9am  To  5pm  Directly every hour ( Include 9 and 17)
// question mark (?): Used only for   Japan (Day of month)  and   week (Day of week), Indicates that no value is specified , Can be used instead of  *

github.com/robfig/cron The package also provides us with some predefined patterns :

entrance describe Equivalent to
@yearly (or @annually) Once a year , At midnight on January 1 0 0 0 1 1 *
@monthly Run once a month , Midnight on the first day of each month 0 0 0 1 * *
@weekly Run once a week , Saturday / Sunday midnight 0 0 0 * * 0
@daily (or @midnight) Run once a day , On the same day at midnight 0 0 0 * * *
@hourly Start running every hour 0 0 * * * *
@every Each duration

Example

c.AddFunc("@every 1h", func() {
     })
原网站

版权声明
本文为[Muzi text_ Ah]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211513306349.html