Timer

Chris wendlec at tcd.ie
Mon Feb 17 06:31:38 PST 2014


On Monday, 17 February 2014 at 12:03:39 UTC, Dejan Lekic wrote:
> On Monday, 17 February 2014 at 11:08:16 UTC, Chris wrote:
>> The D way of implementing a timer? I need to (automatically) 
>> execute a function that performs a clean up, say every hour.
>>
>> if (file.older than 1 hour) {
>>    remove;
>> }
>
> Here is a quick timer implementation that you can improve 
> yourself:
>
> import std.stdio;
> import core.thread;
>
> class ChrisTimer : Thread {
>     private void delegate() funcToRun;
>     private long timeToWait;
>     private bool done = false;
>     private int noSheep;
>     private Duration howLong;
>
>     // We could make any function a parameter to ChrisTimer if 
> we had a
>     // constructor like:
>     // this(void delegate() dg, long ms) {
>
>     this(long ms) {
>         funcToRun = &doSomething;
>         timeToWait = ms;
>         howLong = dur!("msecs")(timeToWait);
>         funcToRun = &doSomething;
>         super(&run);
>     }
>
>     private void run() {
>         while (isRunning && !done) {
>             funcToRun();
>             sleep(howLong);
>         }
>     }
>
>     // Example function that is just going to count sheep (up 
> to 10).
>     public void doSomething() {
>         ++noSheep;
>         writeln("Counted ", noSheep, " sheep.");
>         if (noSheep >= 10) {
>             done = true;
>         }
>     }
>
> } // ChrisThread class
>
> int main(string[] args) {
>     auto ct = new ChrisTimer(2000);
>     ct.start();
>
>     return 0;
> }

Great stuff, thanks for the code example. I feel flattered to 
have my own ChrisTimer now. I'll see which implementation is 
better suited for the task (vibe.d's setTimer or my own thread 
based on your example).


More information about the Digitalmars-d-learn mailing list