In fact, this is quite complicated. Ethereum contracts cannot by themselves start or initiate a transaction at a particular point in time.
You have two options to solve this problem: External calls or a withdraw pattern, see below.
External Calls
At the start of every transaction or chain of transactions (i.e. contracts calling other contracts or sending Ether to other contracts) there needs to be an initial external call by a regular account.
So if you want your contract to send Ether to a predefined address within a particular time window, either you or someone else needs to start this transaction. If you don't want to do it yourself or you are looking for some automated approach, you may want to check out services such as Ethereum Alarm Clock. It is currently working on mainnet. You could also set up a cron job on your own server that starts the transaction if you don't want to use EAC.
Still, bottom line is: You will always need a trusted third party or service that is external to the Ethereum blockchain for scheduled function executions.
Withdraw Pattern Alternative
As an alternative, you could offer the beneficiary of your contract that she or he is allowed to withdraw funds from the contract if a particular point in time is reached:
pragma solidity ^0.6.0;
function withdraw(){
// money can only be withdrawn if time has come
require(block.timestamp > timeHasCome);
// money can only be withdrawn by beneficiary
require(msg.sender == beneficiary);
// make sure beneficiary can only withdraw once
// by deleting his address from the contract's memory
beneficiary = address(0);
// finally send the funds
(bool success, ) = msg.sender.call.value(predefinedAmount)(""); // This forwards all available gas
require(success, "Transfer failed."); // Return value is checked
}
So if timeHasCome
, beneficiary
is allowed to withdraw predefinedAmount
once by calling the withdraw
function of your contract.
Note that block.timestamp
is the time of block creation and is set by the miner. Please note that block.timestamp
can be manipulated within a couple of seconds, so its usage is safe only if you operate on timescales such as hours or days.