run solidity code after every x amount of time

Viewed 5381

I am creating a dev application in which after for example every 5 minutes would like to run some code from my erc20 token's smart contract. How can I call that function after every 5 minutes in solidity?

3 Answers

There's no native delay (sleep, or anything that waits some amount of time) function in Solidity (or in EVM bytecode in general).


Each solidity function is executed as a part of a transaction.

So you can set the timer on your off-chain app, sending a transaction each 5 minutes. Mind that there's a delay between sending a transaction from your app and actually publishing the block (by a miner) that contains the transaction.

Example in JS:

function sendTx() {
   myContract.methods.myFunction().send();
};

setInterval('sendTx', 5 * 1000 * 60);

You can also validate the delay in Solidity and perform an action only if 5 minutes passed since the last action.

pragma solidity ^0.8;

contract MyContract {
    uint256 lastRun;

    function myFunction() external {
        require(block.timestamp - lastRun > 5 minutes, 'Need to wait 5 minutes');

        // TODO perform the action

        lastRun = block.timestamp;
    }
}

You can use Gelato to schedule function calls in your smart contract. https://www.gelato.network/ A very useful tool that takes a smart contract address, a function name and schedule to execute your chosen tasks.

The best way to accomplish this is with Chainlink Keepers. It functions basically as a Cron job that executes a given function in your contract at every interval that you configure.

It can become expensive though, so make sure you know what the cost-benefit is. Or you can deploy on Polygon or other L2 to minimize the cost.

Related