Click here to Skip to main content
15,898,373 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,

This is Ramesh,

My Requirement is "Windows services run only 12.00 a.m every day(i.e midnight)"..But i have to write some Code but not working.

Please once go through the following code as
C#
static void my_task(Object obj)
       {
           Console.WriteLine("task being performed.");
       }

       static TimerCallback timerDelegate;
       static Timer timer;

       static void Main(string[] args)
       {
           DateTime now = DateTime.Now;
           DateTime today = now.Date.AddHours(0);
           DateTime next = now <= today ? today : today.AddDays(1);

           timerDelegate = new TimerCallback(my_task);

           // hence the first,after the next
           timer = new Timer(timerDelegate, null, next - DateTime.Now, TimeSpan.FromHours(24));
       }

I know how to set up the Time intervals i.e Hrs wise,Mint's wise..Etc...When i am searching "Google" it shows that Schedule Tasks is better option all sites,forums..etc instead of Windows Services But My Managers not agree with me...Could you please give me valuable suggestion.

Thanks®ards,

Ramesh.n
Posted
Updated 26-Sep-13 21:21pm
v3
Comments
[no name] 27-Sep-13 10:34am    
A scheduled task is the way to do this. The real solution is to get different managers. A service is way overkill for running a task at a given time of day.

1 solution

Windows services are designed to work all the time until explicitly stopped or until system shutdown. Use your timer only to initiate some action of a working service.

But maybe you don't need your own service at all? If you only need to initiate some action at certain moments of time, you can use already available service, designed specially for this purpose, which can support really complex schedules. It is already bundled with Windows and enabled; you can use it on different levels. It is called Window Task Scheduler, see http://en.wikipedia.org/wiki/Windows_Task_Scheduler[^].

First, you can schedule events using command-line utilities AT.EXE or CSHTASKS.EXE (which is replacing AT.EXE), see:
http://en.wikipedia.org/wiki/At_%28Windows%29[^],
http://en.wikipedia.org/wiki/Schtasks[^],
http://technet.microsoft.com/en-us/library/bb490866.aspx[^],
http://msdn.microsoft.com/en-us/library/windows/desktop/bb736357%28v=vs.85%29.aspx[^].

And you also can use Window Task Scheduler API, please see:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa383614%28v=vs.85%29.aspx[^],
http://msdn.microsoft.com/en-us/library/windows/desktop/aa383608%28v=vs.85%29.aspx[^].

To see how can you use it with .NET, see this CodeProject article: A New Task Scheduler Class Library for .NET[^].

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900