Using Timers in Smart Contracts

--

block.timestamp

A crude, but adequate method of keeping track of time is the block.timestamp method, which returns the time in seconds since the unix epoch (1/1/1970). We can use this method to construct a discrete clock for our contract.

In the Solidity code snippet above, the constructor sets an initial start time. Then we can use a helper function getCurrentCycle() to compute the number of cycles that have elapsed since the contract was deployed.

Conclusion

The block.timestamp method is sufficient for most time-keeping purposes, but it is only accurate up to a few minutes, and most certainly not accurate up to seconds and milliseconds. However, it is a useful building block for discrete clocks and adequate for most applications, such as distributing goods or implementing unlock times.

--

--

A Blueberry Dog

Technical guides and tutorials for the emerging web3 developer community ❤