github.com/blend/go-sdk@v1.20220411.3/examples/cron/immediate/main.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package main
     9  
    10  import (
    11  	"context"
    12  	"os"
    13  
    14  	"github.com/blend/go-sdk/cron"
    15  	"github.com/blend/go-sdk/env"
    16  	"github.com/blend/go-sdk/graceful"
    17  	"github.com/blend/go-sdk/logger"
    18  )
    19  
    20  // NOTE: Ensure that
    21  //       * `InfrequentTask` satisfies `cron.Job`.
    22  //       * `InfrequentTask` satisfies `cron.ScheduleProvider`.
    23  var (
    24  	_ cron.Job              = (*InfrequentTask)(nil)
    25  	_ cron.ScheduleProvider = (*InfrequentTask)(nil)
    26  )
    27  
    28  // Config contains options for the command.
    29  type Config struct {
    30  	ServiceName string `json:"serviceName" yaml:"serviceName" env:"SERVICE_NAME"`
    31  	ServiceEnv  string `json:"serviceEnv" yaml:"serviceEnv" env:"SERVICE_ENV"`
    32  }
    33  
    34  // NewConfigFromEnv returns a new config from the environment.
    35  func NewConfigFromEnv() *Config {
    36  	var config Config
    37  	env.Env().ReadInto(&config)
    38  	return &config
    39  }
    40  
    41  // InfrequentTask extends the lease on vault token.
    42  type InfrequentTask struct {
    43  	Config *Config
    44  	Log    logger.Log
    45  }
    46  
    47  // Name returns the job name.
    48  func (it *InfrequentTask) Name() string {
    49  	return "infrequent_task"
    50  }
    51  
    52  // Schedule returns a schedule for the job.
    53  func (it *InfrequentTask) Schedule() cron.Schedule {
    54  	return cron.Immediately().Then(cron.EverySecond())
    55  }
    56  
    57  // Execute represents the job body.
    58  func (it *InfrequentTask) Execute(ctx context.Context) error {
    59  	sum := 0
    60  	for i := 0; i < 10000; i++ {
    61  		sum += i
    62  	}
    63  	logger.MaybeDebugf(it.Log, "Computed sum: %d", sum)
    64  	return nil
    65  }
    66  
    67  func main() {
    68  	log := logger.All()
    69  	config := NewConfigFromEnv()
    70  	log.Infof("starting `%s` infrequent task daemon", config.ServiceName)
    71  	jm := cron.Default()
    72  	cron.OptLog(log)(jm)
    73  	job := &InfrequentTask{Config: config, Log: log}
    74  	jm.LoadJobs(job)
    75  	if err := graceful.Shutdown(jm); err != nil {
    76  		log.Fatal(err)
    77  		os.Exit(1)
    78  	}
    79  }