1

I have created one thread in C#. Now I want to put the thread that I created into some specific amount of time. And then I want to start my thread. My target is, I want to invoke my updateMark function daily at 8 PM. After invoking my function, then that thread will go to sleep for next 24hours. So it will again start at 8PM of the next day and do the same work routinely.

**My C# code:-**
    public class ThreadProcess
    {
        public static void Main()
        {

        }

        public void updateMark()
        {
             string temp=ok("hai");
        }

        public string ok(string temp)
        {
             return temp+"!!!!";
        }
    }

So, I am using thread in the following code in another class:

        string targetTime = "08:05:00 PM";
        string currentTime = DateTime.Now.ToString("HH:mm:ss tt");

        DateTime t11 = Convert.ToDateTime(targetTime, culture);
        DateTime t21 = Convert.ToDateTime(currentTime, culture);

        ThreadProcess tp = new ThreadProcess();
        Thread myThread = new Thread(tp.updateMark);
        myThread.Start();

        if (t11.TimeOfDay.Ticks > t21.TimeOfDay.Ticks)
        {
            TimeSpan duration = DateTime.Parse(targetTime, culture).Subtract(DateTime.Parse(currentTime, culture));
            int ms = (int)duration.TotalMilliseconds;

            //Thread.Sleep(ms);i want to put my thread into sleep
        }

        while (true)
        {               
            myThread.start();

            Thread.Sleep(86400000);//put thread in sleep mode for next 24 hours...86400000 milleseconds...
        }      

Please guide me to get out of this issue...

mipe34
  • 5,596
  • 3
  • 26
  • 38
Saravanan
  • 11,372
  • 43
  • 143
  • 213
  • Why not simply spawn a process? – bash.d Mar 08 '13 at 12:45
  • 1
    Why not just let [Quartz.NET](http://quartznet.sourceforge.net/) or Windows Task Scheduler solve this? Or if you really must reinvent the wheel, take a look at WaitHandles, as suggested [here](http://stackoverflow.com/questions/8815895/why-is-thread-sleep-so-harmful). – CodeCaster Mar 08 '13 at 12:50

2 Answers2

2

Would it not be more logical to create an object, that has this process stored within it. Then at a certain time, call the run method inside that object, each night. No need for random sleeping threads, and the memory will clean itself up after it's done.

Pseudo-Code

TargetTime := 8:00PM.
// Store the target time.
Start Timer.
// Start the timer, so it will tick every second or something. That's up to you.
function tick()
{
    CurrentTime := current time.
    // Grab the current time.
    if(CurrentTime == TargetTime)
    {
         // If CurrentTime and TargetTime match, we run the code.
         // Run respective method.
    }
}
christopher
  • 26,815
  • 5
  • 55
  • 89
  • Can you little bit elaborate your idea me? – Saravanan Mar 08 '13 at 12:49
  • 2
    In this case, where the interval is very large, I would probably go with a timer-style solution like this one. Could be optimized a bit by setting the initial timer interval to half the total interval then, when fired, recalculate the time left and set the timer to half that.. and so on until close to timeout time. When the remaining time is less than, say, one second, set some 'really run the method on next fire' flag and set the timer for the last time. – Martin James Mar 08 '13 at 13:49
  • @MartinJames: yes you are correct.I just created a C# Console Application and configure the exe in windows sheduled task list...It is doing my job perfectly...Thanks martin for me to enlighten on this... – Saravanan Mar 09 '13 at 09:23
1

I think you should use a timer instead of Thread.Sleep in your case.

There are different types of Timers in .NET, you can read about some of them here.

I would suggest the following simplified implementation based on System.Threading.Timer:

public class ScheduledJob
{
    //Period of time the timer will be raised. 
    //Not too often to prevent the system overload.
    private readonly TimeSpan _period = TimeSpan.FromMinutes(1);
    //08:05:00 PM
    private readonly TimeSpan _targetDayTime = new TimeSpan(20, 5, 0);
    private readonly Action _action;
    private readonly Timer _timer;

    private DateTime _prevTime;

    public ScheduledJob(Action action)
    {
        _action = action;
        _timer = new Timer(TimerRaised, null, 0, _period.Milliseconds);
    }

    private void TimerRaised(object state)
    {
        var currentTime = DateTime.Now;

        if (_prevTime.TimeOfDay < _targetDayTime
            && currentTime.TimeOfDay >= _targetDayTime)
        {
            _action();
        }

        _prevTime = currentTime;
    }
}

And then, in your client code, just call:

var job = new ScheduledJob(() =>
    {
        //Code to implement on timer raised. Run your thread here.
    });
Olexander Ivanitskyi
  • 2,202
  • 17
  • 32