Search code examples
cronethereumsolidityschedule

Schedule call function from smart contract


I woudlike to run everytime my farm function from my smart contract. How can I process to run the function every 3 hours ?


Solution

  • There's no native way implemented in the language, because Solidity functions are executed as a result of a transaction. But you can schedule the transaction to be sent every 3 hours.


    One of the ways is using a cron initiator of a Chainlink job.

    Docs with examples of the job config:


    Or running a script on your server that sends the transaction directly (without using Chainlink as a mediator).

    const Web3 = require('web3');
    const web3 = new Web3(providerUrl);
    const myContract = new web3.eth.Contract(jsonAbi, contractAddress);
    web3.eth.accounts.wallet.add(senderPrivateKey);
    
    async function sendTransaction() {
        myContract.methods.myFunction().send({from: senderAddress});
    }
    
    setInterval('sendTransaction', 3 * 60 * 60 * 1000); // 3 hours in milliseconds