Periodic timers
This guide demonstrates how to create a small dapp with a periodic task. The task is triggered automatically by the ICP network with a specified interval.
Prerequisites
Before getting started, assure you have set up your developer environment according to the instructions in the developer environment guide.
Create the timer dapp project
Open a terminal window on your local computer if you don’t already have one open.
Use dfx new <project_name> --type=rust
to create a new project:
dfx start --clean --background
dfx new my_timers --type=rust
Then, navigate into your project directory by running the command:
cd my_timers
Writing the Cargo.toml file
First, open the src/my_timers_backend/Cargo.toml
file in a code editor. Replace the existing contents with the following:
[package]
name = "my_timers_backend"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
crate-type = ["cdylib"]
[dependencies]
candid = "0.8.2"
ic-cdk = "0.7.0"
ic-cdk-timers = "0.1"
serde = { version = "1.0", features = ["derive"] }
Save the file.
Update the Cargo.toml dependencies
Since you made changes to the Cargo.toml file, run the following command to update the project's dependencies:
cargo update
Declaring the canister interface
Candid is an interface description language (IDL) for interacting with canisters running on ICP. To see details about the Candid interface description language syntax, see the Candid guide or the Candid crate documentation.
Start by opening the src/my_timers_backend/my_timers_backend.did
file in a code editor and replacing its content with the following:
service : (nat64) -> {
"counter": () -> (nat64) query;
}
This code establishes the following:
service : (nat64) -> {...}
: Declares a new service that accepts a single integer argument."counter": () -> (nat64) query
: Declares a canister query entry point namedcounter
. Thecounter
query takes no arguments()
and returns an integer(nat64)
.
Save the file.
Implementing the counter
query
In the previous step, the counter
query is declared as "counter": () -> (nat64) query
. This step implements it.
In the code editor, open the src/my_timers_backend/src/lib.rs
file and replace its content with the following:
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
#[ic_cdk::query]
fn counter() -> u64 {
COUNTER.load(Ordering::Relaxed)
}
This code establishes the following:
static COUNTER: AtomicU64 = ...
: Defines a new global variable calledCOUNTER
.#[ic_cdk::query]
: Marks the followingcounter
function as aquery
entry point, so the function will be exported ascanister_query counter
.fn counter() -> u64 {...}
: Defines the query. Just like in the.did
definition, it takes no arguments and returnsu64
.COUNTER.load(...)
: Loads and returns the globalCOUNTER
value.
It is important to note that Ordering
in this code is a shorter, but equivalent, alternative to thread_local!
wrapping a Cell<u64>
.
Implementing canister initialization
In the previous step, the service is declared as service : (nat64) -> {...}
. This step implements the canister initialization with an argument.
In the code editor, open the src/my_timers_backend/src/lib.rs
file and append the following:
// ...
#[ic_cdk::init]
fn init(timer_interval_secs: u64) {
let interval = std::time::Duration::from_secs(timer_interval_secs);
ic_cdk::println!("Starting a periodic task with interval {interval:?}");
ic_cdk_timers::set_timer_interval(interval, || {
COUNTER.fetch_add(1, Ordering::Relaxed);
});
}
This code establishes the following:
#[ic_cdk::init]
: Marks the followinginit
function as a canister initialization method, so the function will be run when the canister is installed.fn init(interval: u64) {...}
: Defines the initialization method. Just like in the.did
definition, the function takes one argument: timer interval in seconds.ic_cdk::println!(...)
: Prints the debug log message on the localdfx
console.ic_cdk_timers::set_timer_interval(...)
: Creates a new periodic timer with the specified interval and a closure to call.COUNTER.fetch_add(1, ...)
: Increases the globalCOUNTER
every time the periodic task is triggered.
Implementing canister upgrade
Note: As described in the periodic tasks and timers page, the timers library does not handle canister upgrades. It is up to the canister developer to serialize the timers in the canister_pre_upgrade
and reactivate the timers in the canister_post_upgrade
method if needed.
Using pre_ and post_upgrade hooks is discouraged. It is error-prone and can render a canister unusable. Per best practices, using these methods should be avoided if possible.
For the sake of simplicity, in this guide, the canister_post_upgrade
method just calls canister_init
to reinitialize the timer.
In the code editor, open the src/my_timers_backend/src/lib.rs
file and append the following:
// ...
#[ic_cdk::post_upgrade]
fn post_upgrade(timer_interval_secs: u64) {
init(timer_interval_secs)
}
This code establishes the following:
#[ic_cdk::post_upgrade]
: Marks the followingpost_upgrade
function as a canister post-upgrade handler, so the function will be exported ascanister_post_upgrade
.fn post_upgrade(interval: u64) {...}
: Defines the post-upgrade method. Just like in the.did
definition, the function takes one argument: timer interval in seconds.init(timer_interval_secs)
: For the sake of simplicity, the post-upgrade just calls theinit
function, i.e., does exactly the same as the canister initialization.
The canister's code is now complete. The finished file should look like this:
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
#[ic_cdk::query]
fn counter() -> u64 {
COUNTER.load(Ordering::Relaxed)
}
#[ic_cdk::init]
fn init(timer_interval_secs: u64) {
let interval = std::time::Duration::from_secs(timer_interval_secs);
ic_cdk::println!("Starting a periodic task with interval {interval:?}");
ic_cdk_timers::set_timer_interval(interval, || {
COUNTER.fetch_add(1, Ordering::Relaxed);
});
}
#[ic_cdk::post_upgrade]
fn post_upgrade(timer_interval_secs: u64) {
init(timer_interval_secs)
}
Save the file.
Running the dapp locally
The libraries are added, the canister interface is described, and the code is complete. Time to try it all out!
Compile, build, and deploy my_timers_backend
canister, setting the interval for the periodic task to 1s:
dfx deploy my_timers_backend --argument 1
The counter inside the canister starts increasing every second.
Example output:
dfx deploy my_timers_backend --argument 1
[...]
Deployed canisters.
URLs:
Backend canister via Candid interface:
my_timers_backend: http://127.0.0.1/...
Then, observe that the counter is actually non-zero:
dfx canister call my_timers_backend counter
Example output:
dfx canister call my_timers_backend counter
(8 : nat64)