0

I need the simplest possible Timer to repeat my code infinitely every 5 seconds. No external classes or whatnot.

Just:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Now the following code will be repeated over and over");
    
        //////////////// FOLLOWING CODE /////////////////
        /* the repeated code */
        //////////////// END OF FOLLOWING CODE /////////////////

    }
}

How can I do that?

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Totallama
  • 418
  • 3
  • 10
  • 26

5 Answers5

1

Use while(true) with Thread.Sleep

    using System.Threading;

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Now the following code will be repeated over and over");

            while(true)
            {
                //////////////// FOLLOWING CODE /////////////////
                /* the repeated code */
                //////////////// END OF FOLLOWING CODE /////////////////
              Thread.Sleep(5000);
            }   
        }
    }
geothachankary
  • 1,040
  • 1
  • 17
  • 30
1

Use Timer.

static void Main(string[] args)
{

    Timer timer = new System.Threading.Timer((e) =>
    {
        Console.WriteLine("Now the following code will be repeated over and over");
    }, null, 0, (int)TimeSpan.FromSeconds(5).TotalMilliseconds);

    Console.Read();
}

Here I have called Console.WriteLine multiple times, you can write your code block instead of it.

You can use Thread.Sleep(5000); But again its also external class according to the OP.

But I would suggest a better solution using Async and Await. One more thing you should have a termination condition, so that you dont produce an infinite call to avoid unnecessary memory consumption.

public static async Task RepeatActionEveryInterval(Action action, TimeSpan interval, CancellationToken cancelToken)
{
    while (true)
    {
        action();
        Task task = Task.Delay(interval, cancelToken);

        try
        {
            await task;
        }

        catch (TaskCanceledException)
        {
            return;
        }
    }
}


static void Main(string[] args)
{

    CancellationTokenSource cancelToken = new CancellationTokenSource(TimeSpan.FromSeconds(50));
    Console.WriteLine("Start");
    RepeatActionEveryInterval(() => Console.WriteLine("Repeating Code"), TimeSpan.FromSeconds(5), cancelToken.Token).Wait();
    Console.WriteLine("End");
    Console.Read();
}

In this example this code will write till 50 seconds.

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
1

Use this code for call your function recursively for every 5 seconds.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace recurssiveWithThread
{
    class Program
    {

        static void Main(string[] args)
        {

            RecWork();     
        }
        public static int i = 0;
        public static void RecWork()
        {
            // Do the things whatever you needed here 

            i++;
            Console.WriteLine(i);
            //Thread to make the process to sleep for sometimes
            Thread.Sleep(5000);

            //Call your function here
            RecWork();
        }           
    }
}
Tejas R
  • 9
  • 2
  • StackOverflowException. – bhuvin Oct 26 '16 at 06:23
  • Just curious. Is it going to raise a stackoverflow because of the "i++" ? Or did i missed something ? – yan yankelevich Oct 26 '16 at 07:58
  • @yanyankelevich - It will overflow because the function calls itself on every call. That causes memory being allocated on the stack and never freed with each call and therefor eventually the stack will completely be in use after a while and overflow on the next call – Emond Nov 02 '16 at 11:15
  • I did missed something ^^ Thanks for the explanation – yan yankelevich Nov 02 '16 at 12:45
1

Simplest form of it :

using System.Threading;

static void Main(string[] args)
{
    bool breakConditionFlag = false;
    ManualResetEvent waitHandler = new ManualResetEvent(false); 

    while(breakConditionFlag)
    {

    //Your Code

    waitHandler.WaitOne(TimeSpan.FromMilliseconds(1000)); // 1000 is the Arbitary value you can change it to Suit your purpose;

    }
}

Why ManualResetEvent ?

The event makes more efficient use of the processors- you're not having to wake the parent thread up to poll. The kernel will wake you up when the event fires.

bhuvin
  • 1,382
  • 1
  • 11
  • 28
0

Use BackgroundWorker class:

Reference links: Background worker

If you are using framework >= 4.5.2 QueueBackgroundWorkItem

QueueBackgroundWorkItem

Amey Khadatkar
  • 414
  • 3
  • 16