github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/updater/update_checker.go (about)

     1  // Copyright 2015 Keybase, Inc. All rights reserved. Use of
     2  // this source code is governed by the included BSD license.
     3  
     4  package updater
     5  
     6  import "time"
     7  
     8  const DefaultTickDuration = time.Hour
     9  
    10  // UpdateChecker runs updates checks every check duration
    11  type UpdateChecker struct {
    12  	updater      *Updater
    13  	ctx          Context
    14  	ticker       *time.Ticker
    15  	log          Log
    16  	tickDuration time.Duration // tickDuration is the ticker delay
    17  	count        int           // count is number of times we've checked
    18  }
    19  
    20  // NewUpdateChecker creates an update checker
    21  func NewUpdateChecker(updater *Updater, ctx Context, tickDuration time.Duration, log Log) UpdateChecker {
    22  	return UpdateChecker{
    23  		updater:      updater,
    24  		ctx:          ctx,
    25  		log:          log,
    26  		tickDuration: tickDuration,
    27  	}
    28  }
    29  
    30  func (u *UpdateChecker) check() error {
    31  	u.count++
    32  	update, err := u.updater.Update(u.ctx)
    33  	u.ctx.AfterUpdateCheck(update)
    34  	return err
    35  }
    36  
    37  // Check checks for an update.
    38  func (u *UpdateChecker) Check() {
    39  	u.updater.config.SetLastUpdateCheckTime()
    40  	if err := u.check(); err != nil {
    41  		u.log.Errorf("Error in update: %s", err)
    42  	}
    43  }
    44  
    45  // Start starts the update checker. Returns false if we are already running.
    46  func (u *UpdateChecker) Start() bool {
    47  	if u.ticker != nil {
    48  		return false
    49  	}
    50  	u.ticker = time.NewTicker(u.tickDuration)
    51  	go func() {
    52  		// If we haven't done an update recently, check now.
    53  		// If there is an error getting the last update time, we don't trigger a
    54  		// check and let the ticker below trigger it.
    55  		if !u.updater.config.IsLastUpdateCheckTimeRecent(u.tickDuration) {
    56  			u.Check()
    57  		}
    58  
    59  		u.log.Debugf("Starting (ticker %s)", u.tickDuration)
    60  		for range u.ticker.C {
    61  			u.log.Debugf("%s", "Checking for update (ticker)")
    62  			u.Check()
    63  		}
    64  	}()
    65  	return true
    66  }
    67  
    68  // Stop stops the update checker
    69  func (u *UpdateChecker) Stop() {
    70  	if u.ticker != nil {
    71  		u.ticker.Stop()
    72  		u.ticker = nil
    73  	}
    74  }
    75  
    76  // Count is number of times the check has been called
    77  func (u UpdateChecker) Count() int {
    78  	return u.count
    79  }