run solidity code after every x amount of time
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?
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;
}
}