2 Star 2 Fork 9

王布衣/gox

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
cron_job.go 2.09 KB
Copy Edit Raw Blame History
王布衣 authored 2023-07-21 05:10 . 恢复daemon的demo
package main
import (
"fmt"
"gitee.com/quant1x/gox/cron"
"gitee.com/quant1x/gox/daemon"
"log"
"os"
"os/signal"
"syscall"
"time"
)
const (
// name of the service
name = "cron_job"
description = "Cron job service example"
)
var stdlog, errlog *log.Logger
// Service is the daemon service struct
type Service struct {
daemon.Daemon
}
func makeFile() {
// create a simple file (current time).txt
f, err := os.Create(fmt.Sprintf("%s/%s.txt", os.TempDir(), time.Now().Format(time.RFC3339)))
if err != nil {
log.Fatal(err)
}
defer f.Close()
}
// Manage by daemon commands or run the daemon
func (service *Service) Manage() (string, error) {
usage := "Usage: cron_job install | remove | start | stop | status"
// If received any kind of command, do it
if len(os.Args) > 1 {
command := os.Args[1]
switch command {
case "install":
return service.Install()
case "remove":
return service.Remove()
case "start":
return service.Start()
case "stop":
// No need to explicitly stop cron since job will be killed
return service.Stop()
case "status":
return service.Status()
default:
return usage, nil
}
}
// Set up channel on which to send signal notifications.
// We must use a buffered channel or risk missing the signal
// if we're not ready to receive when the signal is sent.
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM)
// Create a new cron manager
c := cron.New()
// Run makefile every min
c.AddFunc("* * * * * *", makeFile)
c.Start()
// Waiting for interrupt by system signal
killSignal := <-interrupt
stdlog.Println("Got signal:", killSignal)
return "Service exited", nil
}
func init() {
stdlog = log.New(os.Stdout, "", log.Ldate|log.Ltime)
errlog = log.New(os.Stderr, "", log.Ldate|log.Ltime)
}
func main() {
srv, err := daemon.New(name, description, daemon.SystemDaemon)
if err != nil {
errlog.Println("Error: ", err)
os.Exit(1)
}
service := &Service{srv}
status, err := service.Manage()
if err != nil {
errlog.Println(status, "\nError: ", err)
os.Exit(1)
}
fmt.Println(status)
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/quant1x/gox.git
git@gitee.com:quant1x/gox.git
quant1x
gox
gox
v1.21.2

Search

0d507c66 1850385 C8b1a773 1850385