github.com/gogf/gf/v2@v2.7.4/os/gcron/gcron_z_example_1_test.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gcron_test
     8  
     9  import (
    10  	"context"
    11  	"os"
    12  	"os/signal"
    13  	"syscall"
    14  	"time"
    15  
    16  	"github.com/gogf/gf/v2/frame/g"
    17  	"github.com/gogf/gf/v2/os/gcron"
    18  	"github.com/gogf/gf/v2/os/glog"
    19  )
    20  
    21  func ExampleCronAddSingleton() {
    22  	gcron.AddSingleton(ctx, "* * * * * *", func(ctx context.Context) {
    23  		glog.Print(context.TODO(), "doing")
    24  		time.Sleep(2 * time.Second)
    25  	})
    26  	select {}
    27  }
    28  
    29  func ExampleCronGracefulShutdown() {
    30  	_, err := gcron.Add(ctx, "*/2 * * * * *", func(ctx context.Context) {
    31  		g.Log().Debug(ctx, "Every 2s job start")
    32  		time.Sleep(5 * time.Second)
    33  		g.Log().Debug(ctx, "Every 2s job after 5 second end")
    34  	}, "MyCronJob")
    35  	if err != nil {
    36  		panic(err)
    37  	}
    38  
    39  	quit := make(chan os.Signal, 1)
    40  	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
    41  
    42  	sig := <-quit
    43  	glog.Printf(ctx, "Signal received: %s, stopping cron", sig)
    44  
    45  	glog.Print(ctx, "Waiting for all cron jobs to complete...")
    46  	gcron.StopGracefully()
    47  	glog.Print(ctx, "All cron jobs completed")
    48  }