Implementing a timer using threads

Dennis Kempin dennis at xardias.net
Mon Jan 29 10:22:54 PST 2007


okay here we go, i have a simple conditional compilation added to use
windows Sleep or linux usleep function.
Maybe someone has use for this simple class. You can decide if the timed
event shall be called once or forever until the process/thread is
terminated.

I have not tested this in windows but it "should" work ;)

regards Dennis

import std.thread;

version(Windows)
{
        extern (C)
        {
                void Sleep(int);        
        }
}

version(linux)
{
        extern (C)
        {
                void usleep(int);       
        }
}

class Timer: Thread
{
        private void delegate() action;
        private int waitTime;
        private bit autoRestart;

        this(int waitTime, void delegate() action, bit autoRestart=false)
        {
                this.action = action;
                this.waitTime = waitTime;
                this.autoRestart = autoRestart;
        }

        protected this(int waitTime, bit autoRestart=false)
        {
                this.waitTime = waitTime;
                this.autoRestart = autoRestart;
        }

        override int run()
        {
                sleep(waitTime);
                execute();
                while(autoRestart)
                {
                        sleep(waitTime);
                        execute();
                }
                return 0;
        }

        void execute()
        {
                action();
        }

        private void sleep(int time)
        {
                version(Windows)
                {
                        Sleep(time);
                }
                
                version(linux)
                {
                        usleep(time*1000);
                }
        }
}


More information about the Digitalmars-d-learn mailing list