github.com/blend/go-sdk@v1.20220411.3/cron/times_schedule.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 cron
     9  
    10  import (
    11  	"fmt"
    12  	"sync"
    13  	"time"
    14  )
    15  
    16  // Interface assertions.
    17  var (
    18  	_ Schedule     = (*TimesSchedule)(nil)
    19  	_ fmt.Stringer = (*TimesSchedule)(nil)
    20  )
    21  
    22  // Times returns a new times schedule that returns a given
    23  // next run time from a schedule only a certain number of times.
    24  func Times(times int, schedule Schedule) *TimesSchedule {
    25  	return &TimesSchedule{
    26  		times:    times,
    27  		left:     times,
    28  		schedule: schedule,
    29  	}
    30  }
    31  
    32  // TimesSchedule is a schedule that only returns
    33  // a certain number of schedule "Next" results
    34  // after which it returns time.Time{} for the next runtime.
    35  type TimesSchedule struct {
    36  	sync.Mutex
    37  
    38  	times    int
    39  	left     int
    40  	schedule Schedule
    41  }
    42  
    43  // Next implements cron.Schedule.
    44  func (ts *TimesSchedule) Next(after time.Time) time.Time {
    45  	ts.Lock()
    46  	defer ts.Unlock()
    47  
    48  	if ts.left > 0 {
    49  		ts.left--
    50  		return ts.schedule.Next(after)
    51  	}
    52  	return Zero
    53  }
    54  
    55  // String returns a string representation of the schedul.e
    56  func (ts *TimesSchedule) String() string {
    57  	if typed, ok := ts.schedule.(fmt.Stringer); ok {
    58  		return fmt.Sprintf("%s %d/%d times", typed.String(), ts.left, ts.times)
    59  	}
    60  	return fmt.Sprintf("%d/%d times", ts.left, ts.times)
    61  }