github.com/blend/go-sdk@v1.20220411.3/examples/cron/timeouts/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  	"math/rand"
    13  	"time"
    14  
    15  	"github.com/blend/go-sdk/cron"
    16  	"github.com/blend/go-sdk/logger"
    17  )
    18  
    19  type emptyJob struct {
    20  	running bool
    21  }
    22  
    23  func (j *emptyJob) Timeout() time.Duration {
    24  	return 2 * time.Second
    25  }
    26  
    27  func (j *emptyJob) Name() string {
    28  	return "printJob"
    29  }
    30  
    31  func (j *emptyJob) Execute(ctx context.Context) error {
    32  	j.running = true
    33  	var runFor = 8 * time.Second
    34  	if rand.Int()%2 == 1 {
    35  		runFor = time.Second
    36  	}
    37  
    38  	alarm := time.After(runFor)
    39  	select {
    40  	case <-alarm:
    41  		j.running = false
    42  		return nil
    43  	case <-ctx.Done():
    44  		j.running = false
    45  		return nil
    46  	}
    47  }
    48  
    49  func (j *emptyJob) OnCancellation(_ *cron.JobInvocation) {
    50  	j.running = false
    51  }
    52  
    53  func (j *emptyJob) Status() string {
    54  	if j.running {
    55  		return "Request in progress"
    56  	}
    57  	return "Request idle."
    58  }
    59  
    60  func (j *emptyJob) Schedule() cron.Schedule {
    61  	return cron.Immediately().Then(cron.Every(10 * time.Second))
    62  }
    63  
    64  func main() {
    65  	jm := cron.New(cron.OptLog(logger.All()))
    66  	jm.LoadJobs(&emptyJob{})
    67  	if err := jm.StartAsync(); err != nil {
    68  		logger.FatalExit(err)
    69  	}
    70  
    71  	for {
    72  		for _, job := range jm.Jobs {
    73  			if job.Current() != nil {
    74  				jm.Log.Infof("job: %s > %s state: running elapsed: %v", job.Name, job.Current().ID, cron.Since(job.Current().Started))
    75  			} else {
    76  				jm.Log.Infof("job: %s state: stopped", job.Name)
    77  			}
    78  		}
    79  
    80  		time.Sleep(1000 * time.Millisecond)
    81  	}
    82  }