2

This question already has an answer here:

If I need to implement a smart contract with a function that should be automatically executed each 1 hour (for example). Any suggestions for how to implement such a smart contract?

marked as duplicate by eth Oct 2 '18 at 4:46

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

If I need to implement a smart contract with a function that should be automatically executed each 1 hour

No, it is not possible within smart contract.

It order to do this you need to run external process which triggers the smart contract's function. It can be custom process(job, service, etc.) as well as oraclize.

1

You must use an external service for that application as smart contracts need to be triggered by an external account. The system AION allows you to do this, you can see examples of this here.

Assume you have a smart contract like this:

contract mycontract{
    uint256 public result;
    function add(uint256 x, uint256 y) public {
        result = x + y;
    } 

}

and you want to calculate this sum every 1 hour as in your question (for the sake of the example).

Aion allows you to schedule the execution of your function in a recursive way. Interfacing your contract with AION, the solution will be like this:

pragma solidity ^0.4.24; 

// this is the interface with AION
contract Aion {
    uint256 public serviceFee;
    function ScheduleCall(uint256 blocknumber, address to, uint256 value, uint256 gaslimit, uint256 gasprice, bytes data, bool schedType) public payable returns (uint,address);

}


contract MyContract{
    uint256 public result;
    Aion aion;

    // This function request to schedule the transaction
    function schedule_add(uint256 x, uint y) public {
        aion = Aion(0xFcFB45679539667f7ed55FA59A15c8Cad73d9a4E);
        bytes memory data = abi.encodeWithSelector(bytes4(keccak256('add(uint256,uint256)')),x,y); 
        uint callCost = 200000*1e9 + aion.serviceFee();
        aion.ScheduleCall.value(callCost)( block.timestamp+1 hour, address(this), 0, 200000, 1e9, data, false);
    }


    // this is your original function
    function add(uint x, uint y) public {
        result = x + y;
    }


    function () public payable {}

}

This can be tested on Ropsten for free. (this example is for ropsten).

There are other systems, see this answer for more details

Hope this helps

Not the answer you're looking for? Browse other questions tagged or ask your own question.