gitee.com/quant1x/gox@v1.21.2/daemon/examples/cron/cron_job.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "gitee.com/quant1x/gox/cron" 6 "gitee.com/quant1x/gox/daemon" 7 "log" 8 "os" 9 "os/signal" 10 "syscall" 11 "time" 12 ) 13 14 const ( 15 // name of the service 16 name = "cron_job" 17 description = "Cron job service example" 18 ) 19 20 var stdlog, errlog *log.Logger 21 22 // Service is the daemon service struct 23 type Service struct { 24 daemon.Daemon 25 } 26 27 func makeFile() { 28 // create a simple file (current time).txt 29 f, err := os.Create(fmt.Sprintf("%s/%s.txt", os.TempDir(), time.Now().Format(time.RFC3339))) 30 if err != nil { 31 log.Fatal(err) 32 } 33 defer f.Close() 34 } 35 36 // Manage by daemon commands or run the daemon 37 func (service *Service) Manage() (string, error) { 38 39 usage := "Usage: cron_job install | remove | start | stop | status" 40 // If received any kind of command, do it 41 if len(os.Args) > 1 { 42 command := os.Args[1] 43 switch command { 44 case "install": 45 return service.Install() 46 case "remove": 47 return service.Remove() 48 case "start": 49 return service.Start() 50 case "stop": 51 // No need to explicitly stop cron since job will be killed 52 return service.Stop() 53 case "status": 54 return service.Status() 55 default: 56 return usage, nil 57 } 58 } 59 // Set up channel on which to send signal notifications. 60 // We must use a buffered channel or risk missing the signal 61 // if we're not ready to receive when the signal is sent. 62 interrupt := make(chan os.Signal, 1) 63 signal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM) 64 65 // Create a new cron manager 66 c := cron.New() 67 // Run makefile every min 68 c.AddFunc("* * * * * *", makeFile) 69 c.Start() 70 // Waiting for interrupt by system signal 71 killSignal := <-interrupt 72 stdlog.Println("Got signal:", killSignal) 73 return "Service exited", nil 74 } 75 76 func init() { 77 stdlog = log.New(os.Stdout, "", log.Ldate|log.Ltime) 78 errlog = log.New(os.Stderr, "", log.Ldate|log.Ltime) 79 } 80 81 func main() { 82 srv, err := daemon.New(name, description, daemon.SystemDaemon) 83 if err != nil { 84 errlog.Println("Error: ", err) 85 os.Exit(1) 86 } 87 service := &Service{srv} 88 status, err := service.Manage() 89 if err != nil { 90 errlog.Println(status, "\nError: ", err) 91 os.Exit(1) 92 } 93 fmt.Println(status) 94 }