How can I set a timer that will automatically execute a function after an arbitrary amount of time while also allowing the contract to concurrently perform other actions?
I have a smart contract that runs elections. It is supposed to be able to end the election by setting election.active = false
after an arbitrary amount of time. The problem is, if I set that timer, then the code won't be able to execute anything until that timer runs out:
function startElection(uint guildID, uint initiator, uint role, uint duration) public {
// this starts the election where users can join to campaign
uint electionID = uint(keccak256(abi.encodePacked(initiator, role, duration, block.timestamp)));
uint startTime = block.timestamp;
uint endTime = startTime + duration;
elections[electionID] = Election(true, guildID, initiator, role, duration, endTime);
emit ElectionInitiated(electionID, guildID, initiator, role, duration, endTime);
watch(electionID); // by executing this function, the contract will get stuck here until the timer runs out
}
function watch(uint electionID) internal view {
Election memory election = elections[electionID];
while (block.timestamp < election.endTime) {}
// now end the election here
election.active = false; // ends the election
emit ElectionEnded(electionID); // emits an event telling me the election has ended
}