How to use timer in IC dfinity rust?

I am combing from django background where we use celery beats and celery for background tasks. Now, we have beats and timer which are two alien options for me.
However, after checking Internet Computer Loading I did not get the point from this. Because, my goal is to create websocket system using websocket gate to help many users communicate with each other.
Goal: I want to create a background task that runs 24/7. In which when user make some actions like Deposit ( I have and IC wallet where users can deposit and withdraw) I want to make a background task that check the deposit and update my data ( increate users balance) and send that to the gateway.

here is a pseudocode

 async fn background_task(){
        async fn onmessage(message) =  {
                 STORE.get_user(message.user_id).set_balance(balance);
                 websocketgate.send({
                      channel : message.user_id,
                      new_balance: balance,
                      message: "Your deposit is successful",
                  });
         } 
       websocketgate.onmessage = onmessage
   }

You cannot have long running tasks on your canister, because otherwise the consensus on the new canister’s state would never be reached.

If you’re familiar with Javascript, you can use ic_cdk_timers like you use setTimeout and setInterval.
In your case, you could set up an interval using set_timer_interval that periodically runs a callback that polls the Ledger canister. But be aware that every execution of the timer’s callback costs you as an inter-canister call as stated in the Timers documentation, so setting a frequent interval will cost you quite a lot.


Regarding this line, I’m not getting exactly why you’re declaring the [IC WebSocket]'s (GitHub - omnia-network/ic-websocket-cdk-rs: IC WebSocket CDK for canisters written in Rust) on_message callback in this hypothetical long running task, and not just in the canister’s init function, as explained in the Step 3 of the IC WebSocket tutorial.

2 Likes