Skip to main content

EXPIRE

Syntax

EXPIRE key seconds [NX | XX | GT | LT]

Module

generic

Categories

fast keyspace write

Description

Expire the key in the specified number of seconds. This commands turns a key into a volatile one.

Options

  • NX - Only set the expiry time if the key has no associated expiry.
  • XX - Only set the expiry time if the key already has an expiry time.
  • GT - Only set the expiry time if the new expiry time is greater than the current one.
  • LT - Only set the expiry time if the new expiry time is less than the current one.

NX, GT, and LT are mutually exclusive. XX can additionally be passed in with either GT or LT.

Examples

The embedded API utilizes the ExpireOptions interface, which acts as a wrapper for the various expiry options.


ExpireOptions include the following constants:

  • NX - Only set the expiry time if the key has no associated expiry.
  • XX - Only set the expiry time if the key already has an expiry time.
  • GT - Only set the expiry time if the new expiry time is greater than the current one.
  • LT - Only set the expiry time if the new expiry time is less than the current one.

Add an expiration to a key:

db, err := sugardb.NewSugarDB()
if err != nil {
log.Fatal(err)
}
ok, err := db.Expire("key", 10, nil)

Add an expiration to a key only if it does not have one already:

db, err := sugardb.NewSugarDB()
if err != nil {
log.Fatal(err)
}
ok, err := db.Expire("key", 10, sugardb.NX)

Add an expiration to a key only if it has one already:

db, err := sugardb.NewSugarDB()
if err != nil {
log.Fatal(err)
}
ok, err := db.Expire("key", 10, sugardb.XX)

Add an expiration to a key only if it already has one that is less than the current expiry:

db, err := sugardb.NewSugarDB()
if err != nil {
log.Fatal(err)
}
ok, err := db.Expire("key", 10, sugardb.XX, sugardb.LT)