...

Source file src/github.com/antonlindstrom/pgstore/cleanup.go

Documentation: github.com/antonlindstrom/pgstore

     1  package pgstore
     2  
     3  import (
     4  	"log"
     5  	"time"
     6  )
     7  
     8  var defaultInterval = time.Minute * 5
     9  
    10  // Cleanup runs a background goroutine every interval that deletes expired
    11  // sessions from the database.
    12  //
    13  // The design is based on https://github.com/yosssi/boltstore
    14  func (db *PGStore) Cleanup(interval time.Duration) (chan<- struct{}, <-chan struct{}) {
    15  	if interval <= 0 {
    16  		interval = defaultInterval
    17  	}
    18  
    19  	quit, done := make(chan struct{}), make(chan struct{})
    20  	go db.cleanup(interval, quit, done)
    21  	return quit, done
    22  }
    23  
    24  // StopCleanup stops the background cleanup from running.
    25  func (db *PGStore) StopCleanup(quit chan<- struct{}, done <-chan struct{}) {
    26  	quit <- struct{}{}
    27  	<-done
    28  }
    29  
    30  // cleanup deletes expired sessions at set intervals.
    31  func (db *PGStore) cleanup(interval time.Duration, quit <-chan struct{}, done chan<- struct{}) {
    32  	ticker := time.NewTicker(interval)
    33  
    34  	defer func() {
    35  		ticker.Stop()
    36  	}()
    37  
    38  	for {
    39  		select {
    40  		case <-quit:
    41  			// Handle the quit signal.
    42  			done <- struct{}{}
    43  			return
    44  		case <-ticker.C:
    45  			// Delete expired sessions on each tick.
    46  			err := db.deleteExpired()
    47  			if err != nil {
    48  				log.Printf("pgstore: unable to delete expired sessions: %v", err)
    49  			}
    50  		}
    51  	}
    52  }
    53  
    54  // deleteExpired deletes expired sessions from the database.
    55  func (db *PGStore) deleteExpired() error {
    56  	_, err := db.DbPool.Exec("DELETE FROM http_sessions WHERE expires_on < now()")
    57  	return err
    58  }
    59  

View as plain text