Timer in D.API?

Steve Schveighoffer schveiguy at yahoo.com
Wed Mar 4 07:41:05 PST 2009


On Tue, 03 Mar 2009 23:10:07 -0500, Sam Hu wrote:

> First of all,this is about D ,not C#. In C# the program print each
> letter of a string per 0.3 second one by one using the Timer & delegate:
> C# code:
> using System;
> using System.Text;
> using System.Timers;
> 
> namespace OneLetterATime
> {
>     class Program
>     {
>         static int counter = 0;
>         static string displayString = @"This string will appear one
>         letter at a time."; static void Main(string[] args)
>         {
>             Timer myTimer = new Timer(300);
>             myTimer.Elapsed += new ElapsedEventHandler(WriteChar);
>             myTimer.Start();
>             Console.ReadKey();
> 
> 
>         }
>         static void WriteChar(Object sender, ElapsedEventArgs e) {
>             Console.Write(displayString[counter++%
displayString.Length]);
>         }
>     }
> I would like to implement the same demand using D+Tango: D code:
> module OneLetterATime;
> 
> import tango.io.Stdout;
> import tango.core.Thread;
> //import samsTools.PromptMessage;
> 
> int main(char[][] args)
> {
>   static int counter=0;
>   static char[] displayString=r"This string will appear one letter at a
>   time."; void writeChar()
>   {
>     Thread thisThread=Thread.getThis;
>     for(int counter=0;;counter++)
>     {
>       Stdout.format("{}",displayString[counter%
displayString.length]).flush;
>       thisThread.sleep(0.3);
>     }
> 
>   }
>   Thread thread=new Thread(&writeChar); thread.start;
> 
>   return 0;
> }
> But I am not sure whether this is the right D way to meet the goal.

It depends on how accurate you want it.  Sleeping is guaranteed to sleep 
for at least the amount of time asked for, but it can sleep for longer.  
So it's possible your characters will come out slightly slower.  To 
account for this, you need to use the current time to adjust your sleep 
time.

e.g.:
import tango.time.Clock;
...
auto curTime = Clock.now;
auto period = TimeSpan.fromMilliseconds(300);
auto nextTime = curTime + period;
for(int counter=0;;counter++)
{
  Stdout(displayString[counter%displayString.length]).flush;
  auto timeToSleep = nextTime - curTime;
  if(timeToSleep > TimeSpan.zero)
    Thread.sleep(timeToSleep.interval);
  curTime = Clock.now;
  nextTime += period;
}

> Also
> I would like to know how to abort the program in D as the same does in
> the above C# program that the program aborts when the user press any
> key(Console.ReadKey();)?

tango.stdc.stdlib.exit(int retval)
This will terminate all threads in the process.

> Finally I would like to know is there any API in
> D or Tango that does the same job as Timer in Windows?
> 

As far as I know, there is no such class in Tango.
Not sure about other libs.

-Steve


More information about the Digitalmars-d-learn mailing list