1

I thought of writing a code which will trigger a method Processmethod everyday morning at 06:00 am, somehow I managed to write following code, but it's not generic. How can I make it start at 06:00 am with less code?

while(true) {
    Thread.sleep(Timespan.FromHours(11))
    Processmethod();
}
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
peter
  • 8,158
  • 21
  • 66
  • 119

2 Answers2

2

You have to implement scheduler task for this. There are many dlls available to do this task. for example you can use Quartz.Net. First of all create a job to be executed-

 public class EmailJob : IJob
{
    public void Execute(IJobExecutionContext context)
    {
       // implement your method here

    }
}

Now specify this job to the scheduler -

   public class JobScheduler
{
    public static void Start()
    {
        IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
        scheduler.Start();

        IJobDetail job = JobBuilder.Create<EmailJob>().Build();

        ITrigger trigger = TriggerBuilder.Create()
            .WithDailyTimeIntervalSchedule
              (s =>
                 s.WithIntervalInHours(24)
                .OnEveryDay()
                .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(0, 0))
              )
            .Build();

        scheduler.ScheduleJob(job, trigger);
    }
}

Now specify JobScheduler.Start(); in Application_Start in your global.asax

Vivek Mishra
  • 1,772
  • 1
  • 17
  • 37
  • I used windows sheduler to do this, but the main issue was some times it leaves the intermediate exe is opened state.I need a simple way like what i did – peter Dec 27 '15 at 15:10
  • 1
    @peter you should not use Thread.sleep for this. because it keeps the thread blocked for that time duration and keeps your resources allocated to that thread which may be very harmful for your application. Secondly you can specify time duration for thread to sleep not specific time stamp. – Vivek Mishra Dec 27 '15 at 15:22
  • I will create a window service will use the logic – peter Dec 27 '15 at 17:19
1

You could try the follwing code

while(true)
{
    if(DateTime.Now.Hour == 6 && DateTime.Now.Minute == 0)
       Processmethod();
    else
       Thread.Sleep(1000)
}
Ahmed Anwar
  • 688
  • 5
  • 25
  • only Thread.Sleep(1000)? i think i have to make it to 24 hour gap – peter Dec 27 '15 at 15:27
  • 1
    What I suggested was that it would sleep for one second (1000 milliseconds) and then check on the condition to see whether it's 06:00 am yet. Once it turns 06:00 am the function will be called. I think this makes more sense than making it sleep for 24 hours because if you do call sleep(*24 hours*) you might miss the 06:00 am. Unless you keep calling sleep until it turns 6 , executing the function then calling sleep for 24 hours. Am I making sense to you? – Ahmed Anwar Dec 27 '15 at 15:37