简体   繁体   中英

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 ?

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

You can accomplish this type of 'smart contract cron' or 'smart contract scheduler' completely on chain using Chainlink Keepers. I'd recommend following the sample Keepers contract from the Chinalink docs, where you can set a time interval (in your case, every 3 hours). After the 3 hour interval has passed, you can define which smart contract function you want to automate within the performUpkeep function: https://docs.chain.link/docs/chainlink-keepers/compatible-contracts/#example-contract

Once you've written that contract, register it on the Keepers network at keepers.chain.link to begin the automation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM