Timer
Dejan Lekic
dejan.lekic at gmail.com
Mon Feb 17 04:03:37 PST 2014
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;
}
More information about the Digitalmars-d-learn
mailing list