Stefan
Stefan

Reputation: 59

Have tasks permanently run in background in Console application

I will start off by describing what I want to achieve. The idea is that I have multiple objects of a class with their own different timers. When a timer for an object runs out, I want that object to print a message to the console and then reset the timer. I would like this to run in the background so that my Application can keep working while these multiple timers run in the background.

For example initialise like so (where argument is the timer in seconds):

BackGroundTimer timer1 = new BackGroundTimer(1);
BackGroundTimer timer2 = new BackGroundTimer(2);
BackGroundTimer timer3 = new BackGroundTimer(3);

Console.ReadLine();

Where Console.ReadLine() symbolizes ongoing work. Then I would ideally like to have the following outputs:

0:

1: Timer1

2: Timer1 Timer2

3: Timer1 Timer3

4: Timer1 Timer2

Is this possible to achieve?

Upvotes: 2

Views: 1038

Answers (1)

Prorock
Prorock

Reputation: 85

Take a look at Timer class. You can specify the period in its constructor and it will call specified method periodically.

Edit: Code sample below

static void Main(string[] args)
{
    Timer timer1 = new Timer(1000)
    {
        Enabled = true,
        AutoReset = true
    };

    Timer timer2 = new Timer(2000)
    {
        Enabled = true,
        AutoReset = true
    };

    Timer timer3 = new Timer(3000)
    {
        Enabled = true,
        AutoReset = true
    };

    timer1.Elapsed += async (sender, e) => await HandleTimer("Timer1");
    timer2.Elapsed += async (sender, e) => await HandleTimer("Timer2");
    timer3.Elapsed += async (sender, e) => await HandleTimer("Timer3");

    Console.ReadLine();
}

private static async Task HandleTimer(string message)
{
    Console.WriteLine(message);
}

Upvotes: 4

Related Questions