package cmd import ( "pcgamedb/log" "pcgamedb/task" "github.com/robfig/cron/v3" "github.com/spf13/cobra" "go.uber.org/zap" ) type taskCommandConfig struct { Cron string Now bool } var taskCommandCfg taskCommandConfig var crawlTaskCmd = &cobra.Command{ Use: "crawl", Long: "Start crawl task", Short: "Start crawl task", Run: func(cmd *cobra.Command, args []string) { if taskCommandCfg.Now { task.Crawl(log.Logger) } c := cron.New() _, err := c.AddFunc(taskCommandCfg.Cron, func() { task.Crawl(log.Logger) }) if err != nil { log.Logger.Error("Failed to add task", zap.Error(err)) } c.Start() select {} }, } var updateTaskCmd = &cobra.Command{ Use: "update", Long: "Start update outdated game infos task", Short: "Start update outdated game infos task", Run: func(cmd *cobra.Command, args []string) { if taskCommandCfg.Now { task.UpdateOutdatedGameInfos(log.Logger) } c := cron.New() _, err := c.AddFunc(taskCommandCfg.Cron, func() { task.UpdateOutdatedGameInfos(log.Logger) }) if err != nil { log.Logger.Error("Failed to add task", zap.Error(err)) } c.Start() select {} }, } var taskCmd = &cobra.Command{ Use: "task", Long: "Start task", Short: "Start task", } func init() { crawlTaskCmd.Flags().StringVar(&taskCommandCfg.Cron, "cron", "0 */3 * * *", "cron expression") crawlTaskCmd.Flags().BoolVar(&taskCommandCfg.Now, "now", false, "run task immediately") updateTaskCmd.Flags().StringVar(&taskCommandCfg.Cron, "cron", "0 */3 * * *", "cron expression") updateTaskCmd.Flags().BoolVar(&taskCommandCfg.Now, "now", false, "run task immediately") taskCmd.AddCommand(crawlTaskCmd) taskCmd.AddCommand(updateTaskCmd) RootCmd.AddCommand(taskCmd) }