job

package
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 28, 2021 License: MIT Imports: 24 Imported by: 0

README

cmd/job

注册定时任务请参考 demo.go

查看所有定时任务

go run main.go job list

执行一次某个任务

go run main.go job once foo

go run main.go job once --http=true baz

调度所有定时任务

go run main.go job

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Cmd = &cobra.Command{
	Use:   "job",
	Short: "Run job",
	Long: `You can list all jobs and run certain one once.
If you run job cmd WITHOUT any sub cmd, job will be sheduled like cron.`,
	Run: func(cmd *cobra.Command, args []string) {

		server := &httpd.Server{Addr: fmt.Sprintf(":%d", port)}
		go func() {
			metricsHandler := promhttp.Handler()
			httpd.HandleFunc("/metrics", func(w httpd.ResponseWriter, r *httpd.Request) {
				util.GatherMetrics()

				metricsHandler.ServeHTTP(w, r)
			})

			httpd.HandleFunc("/ListTasks", func(w httpd.ResponseWriter, r *httpd.Request) {
				ctx := context.Background()
				span, ctx := opentracing.StartSpanFromContext(ctx, "ListTasks")
				defer span.Finish()

				w.Header().Set("x-trace-id", trace.GetTraceID(ctx))
				w.Header().Set("content-type", "application/json")

				buf, err := json.Marshal(httpJobs)
				if err != nil {
					w.WriteHeader(httpd.StatusInternalServerError)
					w.Write([]byte(err.Error()))
					return
				}

				w.Write(buf)
			})

			httpd.HandleFunc("/RunTask", func(w httpd.ResponseWriter, r *httpd.Request) {
				ctx := context.Background()
				span, ctx := opentracing.StartSpanFromContext(ctx, "RunTask")
				defer span.Finish()

				w.Header().Set("x-trace-id", trace.GetTraceID(ctx))

				name := r.FormValue("name")
				job, ok := httpJobs[name]
				if !ok {
					w.WriteHeader(httpd.StatusNotFound)
					w.Write([]byte("job " + name + " not found\n"))
					return
				}

				if err := job.job(ctx); err != nil {
					w.WriteHeader(httpd.StatusInternalServerError)
					w.Write([]byte(fmt.Sprintf("%+v", err)))
					return
				}

				w.Write([]byte("run job " + name + " done\n"))
			})

			httpd.HandleFunc("/monitor/ping", func(w httpd.ResponseWriter, r *httpd.Request) {
				w.Write([]byte("pong"))
			})

			if err := server.ListenAndServe(); err != nil {
				panic(err)
			}
		}()

		go func() {
			conf.OnConfigChange(func() { util.Reset() })
			conf.WatchConfig()

			c.Run()
		}()

		stop := make(chan os.Signal, 1)
		signal.Notify(stop, syscall.SIGTERM, syscall.SIGINT)
		<-stop

		var wg sync.WaitGroup
		go func() {
			wg.Add(1)
			defer wg.Done()

			c.Stop()
		}()
		go func() {
			wg.Add(1)
			defer wg.Done()

			err := server.Shutdown(context.Background())
			if err != nil {
				panic(err)
			}
		}()
		wg.Wait()
	},
}

Cmd run job once or periodically

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL