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;
}
}

- 40,554
- 8
- 72
- 100
-
7Appreciated. Say I want my token to be decentralised, I wouldn't want to call these functions by myself. Is there any industry accepted way for triggering them? – geo10 Jun 17 '21 at 18:39
-
4There are semi-decentralized oracle services that do the same thing as the off-chain app in my answer. For example [Chainlink Alarm Clock](https://docs.chain.link/docs/chainlink-alarm-clock/) - you can define your (contract) callback function in a way that keeps resetting the sleep interval to another 5 minutes after it's been executed. But each call (from Chainlink to your contract) costs 0.1 LINK, which can become costly to maintain. – Petr Hejda Jun 17 '21 at 18:50
-
5You could also build a bounty into the smart contract that allows anyone to call the function and if enough time has passed it will pay out a reward to the caller, so long as its even slightly profitable there will probably be someone who puts a bot on it to collect the bounty every 5 minutes. May be able to get cheaper than 0.1 LINK with that solution. – Albert Renshaw Dec 28 '21 at 09:53
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.

- 31
- 1
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.

- 105
- 1
- 4