github.com/wangyougui/gf/v2@v2.6.5/os/gcron/gcron_schedule_fix.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/wangyougui/gf.
     6  
     7  package gcron
     8  
     9  import (
    10  	"context"
    11  	"time"
    12  
    13  	"github.com/wangyougui/gf/v2/internal/intlog"
    14  )
    15  
    16  // getAndUpdateLastCheckTimestamp checks fixes and returns the last timestamp that have delay fix in some seconds.
    17  func (s *cronSchedule) getAndUpdateLastCheckTimestamp(ctx context.Context, t time.Time) int64 {
    18  	var (
    19  		currentTimestamp   = t.Unix()
    20  		lastCheckTimestamp = s.lastCheckTimestamp.Val()
    21  	)
    22  	switch {
    23  	// Often happens, timer triggers in the same second.
    24  	// Example:
    25  	// lastCheckTimestamp:    10
    26  	// currentTimestamp: 10
    27  	case
    28  		lastCheckTimestamp == currentTimestamp:
    29  		lastCheckTimestamp += 1
    30  
    31  	// Often happens, no latency.
    32  	// Example:
    33  	// lastCheckTimestamp:    9
    34  	// currentTimestamp: 10
    35  	case
    36  		lastCheckTimestamp == currentTimestamp-1:
    37  		lastCheckTimestamp = currentTimestamp
    38  
    39  	// Latency in 3 seconds, which can be tolerant.
    40  	// Example:
    41  	// lastCheckTimestamp:    7/8
    42  	// currentTimestamp: 10
    43  	case
    44  		lastCheckTimestamp == currentTimestamp-2,
    45  		lastCheckTimestamp == currentTimestamp-3:
    46  		lastCheckTimestamp += 1
    47  
    48  	// Too much latency, it ignores the fix, the cron job might not be triggered.
    49  	default:
    50  		// Too much delay, let's update the last timestamp to current one.
    51  		intlog.Printf(
    52  			ctx,
    53  			`too much latency, last timestamp "%d", current "%d", latency "%d"`,
    54  			lastCheckTimestamp, currentTimestamp, currentTimestamp-lastCheckTimestamp,
    55  		)
    56  		lastCheckTimestamp = currentTimestamp
    57  	}
    58  	s.lastCheckTimestamp.Set(lastCheckTimestamp)
    59  	return lastCheckTimestamp
    60  }