Start windows Service at multiple times - c#

I writing a windows c# service and I have to start my Service at different time. The times are not fixed they are dynamic and can be more than one in a day let say at time1: 11:50 am, time2: 12:50 pm, time1: 16:24 pm. My service starts correctly at the 1st time only but then it just starting randomly
this is my Code
foreach (var timer in args)
{
_timer = new System.Timers.Timer();
_timer.Enabled = true;
_scheduleTime = Convert.ToDateTime(timer);
_timer.Interval = _scheduleTime.Subtract(DateTime.Now).TotalSeconds * 1000;
_timer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Elapsed);
}
Timer_Elapsed code is:
protected void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
//onDebug();
Console.WriteLine("Completed Successfully");
Log.writeFile("Completed Successfully");
if (_timer.Interval != 24 * 60 * 60 * 1000)
{
_timer.Interval = 24 * 60 * 60 * 1000;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
What I want to do is start service at the time given in the array args
Thanks

Related

call a method only in 30th and 0th second of every minute c#

I have a method which does some calculations.
public void CalculateItems()
{
// Calculate the empty Items
}
Which I need to execute in every 30th second of a minute.
If my service starts at 10:00:15, The method should start working from 10:00:30, 10:01:00, 10:01:30 and goes on.
If my Service starts at 10:00:50, The method should start working from 10:01:00, 10:01:30, 10:02:00 and goes on.
I have tried System.Threading.Timer, System.Timers.Timer but in all these, I couldn't achieve my scenario. Please help with your valuable suggestions.
What I have tried is in System.Threading.Timer
var timer = new System.Threading.Timer(
e => CalculateItems(),
null,
TimeSpan.Zero,
TimeSpan.FromSeconds(30));
But it hits my method every 30th second Not in 30th second of every minute
One simple way to solve it using a timer is to set the interval to a single second, and in the timer's callback method to check if the value of DateTime.Now.Seconds divides by 30:
void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
if(DateTime.Now.Seconds % 30 == 0)
{
CalculateItems();
}
}
You can initially start the timer with 1 second interval. Then in the Timer Event, if DateTime.Now.Second is 30 or 0, You can set the interval to 30 seconds. From then on your event would be triggered only at specified time.
System.Timers.Timer timer= new System.Timers.Timer(1000);
private void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
if(timer.Interval!=30000 && DateTime.Now.Seconds % 30 == 0)
{
timer.Stop();
timer.Interval = 30000;
timer.Start();
DoWork();
}
else
{
if(timer.Interval==30000)
{
DoWork();
}
}
}
I solved it with timers, and calculating the sime to the next 30 sec block:
It is recalculating the 30 sec again after elapsed, otherwise it will slightly get a delta after each run.
class Program
{
static System.Threading.Timer _ttimer;
static void Main(string[] args)
{
SetupTimerTo30sec();
Console.ReadLine();
}
private static void SetupTimerTo30sec()
{
var now = DateTime.Now;
int diffMilliseconds;
if (now.Second < 30)
{
diffMilliseconds = (30 - now.Second) * 1000;
}
else
{
diffMilliseconds = (60 - now.Second) * 1000;
}
diffMilliseconds -= now.Millisecond;
if (_ttimer != null)
{
_ttimer.Change(diffMilliseconds, 30 * 1000);
}
else
{
_ttimer = new Timer(OnElapsed, null, diffMilliseconds, 30 * 1000);
}
}
private static void OnElapsed(object state)
{
Console.Write(DateTime.Now.ToLongTimeString());
Console.WriteLine($":{DateTime.Now.Millisecond}");
SetupTimerTo30sec();
}
}

Executing method every hour on the hour

I want to execute a method every hour on the hour. I wrote some code,but it is not enough for my aim. Below code is working every 60 minutes.
public void Start()
{
System.Threading.Timer timerTemaUserBilgileri = new System.Threading.Timer(new System.Threading.TimerCallback(RunTakip), null, tmrTemaUserBilgileri, 0);
}
public void RunTakip(object temauserID)
{
try
{
string objID = "6143566557387";
EssentialMethod(objID);
TimeSpan span = DateTime.Now.Subtract(lastRunTime);
if (span.Minutes > 60)
{
tmrTemaUserBilgileri = 1 * 1000;
timerTemaUserBilgileri.Change(tmrTemaUserBilgileri, 0);
}
else
{
tmrTemaUserBilgileri = (60 - span.Minutes) * 60 * 1000;
timerTemaUserBilgileri.Change(tmrTemaUserBilgileri, 0);
}
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
}
catch (Exception ex)
{
timerTemaUserBilgileri.Change(30 * 60 * 1000, 0);
Utils.LogYaz(ex.Message.ToString());
}
}
public void EssentialMethod(objec obj)
{
//some code
lastRunTime = DateTime.Now;
//send lastruntime to sql
}
If you want your code to be executed every 60 minutes:
aTimer = new System.Timers.Timer(60 * 60 * 1000); //one hour in milliseconds
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Start();
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
//Do the stuff you want to be done every hour;
}
if you want your code to be executed every hour (i.e. 1:00, 2:00, 3:00) you can create a timer with some small interval (let's say a second, depends on precision you need) and inside that timer event check if an hour has passed
aTimer = new System.Timers.Timer(1000); //One second, (use less to add precision, use more to consume less processor time
int lastHour = DateTime.Now.Hour;
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Start();
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
if(lastHour < DateTime.Now.Hour || (lastHour == 23 && DateTime.Now.Hour == 0))
{
lastHour = DateTime.Now.Hour;
YourImportantMethod(); // Call The method with your important staff..
}
}
I agree with SeƱor Salt that the chron job should be the first choice. However, the OP asked for every hour on the hour from c#. To do that, I set up the first timed event to fire on the hour:
int MilliSecondsLeftTilTheHour()
{
int interval;
int minutesRemaining = 59 - DateTime.Now.Minute;
int secondsRemaining = 59 - DateTime.Now.Second;
interval = ((minutesRemaining * 60) + secondsRemaining) * 1000;
// If we happen to be exactly on the hour...
if (interval == 0)
{
interval = 60 * 60 * 1000;
}
return interval;
}
Timer timer = new Timer();
timer.Tick += timer_Tick;
timer.Enabled = true;
timer.Interval = MilliSecondsLeftTilTheHour();
The problem now is that if the above timer.Interval happens to be 45 minutes and 32 seconds, then the timer will continue firing every 45:32 not just the first time. So, inside the timer_Tick method, you have to readjust the timer.Interval to one hour.
void timer_Tick(object sender, EventArgs e)
{
// The Interval could be hard wired here to 60 * 60 * 1000 but on clock
// resets and if the job ever goes longer than an hour, why not
// recalculate once an hour to get back on track.
timer.Interval = MilliSecondsLeftTilTheHour();
DoYourThing();
}
Just a small comment based on /Anarion's solution that I couldn't fit into a comment.
you can create a timer with some small interval (let's say a second, depends on precision you need)
You don't need it to go with any precision at all, you're thinking "how do I check this hour is the hour I want to fire". You could alternatively think "How do I check the next hour is the hour I want to fire" - once you think like that you realise you don't need any precision at all, just tick once an hour, and set a thread for the next hour. If you tick once an hour you know you'll be at some point before the next hour.
Dim dueTime As New DateTime(Date.Today.Year, Date.Today.Month, Date.Today.Day, DateTime.Now.Hour + 1, 0, 0)
Dim timeRemaining As TimeSpan = dueTime.Subtract(DateTime.Now)
t = New System.Threading.Timer(New System.Threading.TimerCallback(AddressOf Method), Nothing, CType(timeRemaining.TotalMilliseconds, Integer), System.Threading.Timeout.Infinite)
How about something simpler? Use a one-minute timer to check the hour:
public partial class Form1 : Form
{
int hour;
public Form1()
{
InitializeComponent();
if(RunOnStartUp)
hour = -1;
else
hour = DateTime.Now.Hour;
}
private void timer1_Tick(object sender, EventArgs e)
{
// once per minute:
if(DateTime.Now.Hour != hour)
{
hour = DateTime.Now.Hour;
DailyTask();
}
}
private DailyTask()
{
// do something
}
}
Use a Cron Job on the server to call a function at the specified interval
Heres a link
http://www.thesitewizard.com/general/set-cron-job.shtml
What about trying the below code, the loop is determined to save your resources, and it is running every EXACT hour, i.e. with both minutes and seconds (and almost milliseconds equal to zero:
using System;
using System.Threading.Tasks;
namespace COREserver{
public static partial class COREtasks{ // partial to be able to split the same class in multiple files
public static async void RunHourlyTasks(params Action[] tasks)
{
DateTime runHour = DateTime.Now.AddHours(1.0);
TimeSpan ts = new TimeSpan(runHour.Hour, 0, 0);
runHour = runHour.Date + ts;
Console.WriteLine("next run will be at: {0} and current hour is: {1}", runHour, DateTime.Now);
while (true)
{
TimeSpan duration = runHour.Subtract(DateTime.Now);
if(duration.TotalMilliseconds <= 0.0)
{
Parallel.Invoke(tasks);
Console.WriteLine("It is the run time as shown before to be: {0} confirmed with system time, that is: {1}", runHour, DateTime.Now);
runHour = DateTime.Now.AddHours(1.0);
Console.WriteLine("next run will be at: {0} and current hour is: {1}", runHour, DateTime.Now);
continue;
}
int delay = (int)(duration.TotalMilliseconds / 2);
await Task.Delay(30000); // 30 seconds
}
}
}
}
Why is everyone trying to handle this problem with a timer?
you're doing two things... waiting until the top of the hour and then running your timer every hour on the hour.
I have a windows service where I needed this same solution. I did my code in a very verbose way so that it is easy to follow for anyone. I know there are many shortcuts that can be implemented, but I leave that up to you.
private readonly Timer _timer;
/// starts timer
internal void Start()
{
int waitTime = calculateSleepTime();
System.Threading.Thread.Sleep(waitTime);
object t = new object();
EventArgs e = new EventArgs();
CheckEvents(t, e);
_timer.Start();
}
/// runs business logic everytime timer goes off
internal void CheckEvents(object sender, EventArgs e)
{
// do your logic here
}
/// Calculates how long to wait until the top of the hour
private int calculateSleepTime()
{
DateTime now = DateTime.Now;
int minutes = now.Minute * 60 * 1000;
int seconds = now.Second * 1000;
int substrahend = now.Millisecond + seconds + minutes;
int minuend = 60 * 60 * 1000;
return minuend - substrahend;
}
Here's a simple, stable (self-synchronizing) solution:
while(true) {
DoStuff();
var now = DateTime.UtcNow;
var previousTrigger = new DateTime(now.Year, now.Month, now.Day, now.Hour, 0, 0, now.Kind);
var nextTrigger = previousTrigger + TimeSpan.FromHours(1);
Thread.Sleep(nextTrigger - now);
}
Note that iterations may be skipped if DoStuff() takes longer than an hour to execute.

Windows Service - How to make task run at several specific times?

I have a windows service running. Within it the task runs currently at 7pm every day.
What is the best way to have it run say fir example at 9.45am, 11.45am, 2pm, 3.45pm, 5pm and 5.45pm.
I know i can have scheduled task to run the function but i would like to know how to do this within my windows service. Current code below:
private Timer _timer;
private DateTime _lastRun = DateTime.Now;
private static readonly log4net.ILog log = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected override void OnStart(string[] args)
{
// SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
// test.Import();
log.Info("Info - Service Started");
_timer = new Timer(10 * 60 * 1000); // every 10 minutes??
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start();
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
log.Info("Info - Check time");
DateTime startAt = DateTime.Today.AddHours(19);
if (_lastRun < startAt && DateTime.Now >= startAt)
{
// stop the timer
_timer.Stop();
try
{
log.Info("Info - Import");
SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
test.Import();
}
catch (Exception ex) {
log.Error("This is my error - ", ex);
}
_lastRun = DateTime.Now;
_timer.Start();
}
}
In case you dont want to go for cron or quartz, write a function to find time interval between now and next run and reset the timer accordingly, call this function on service start and timeelapsed event. You may do something like this (code is not tested)
System.Timers.Timer _timer;
List<TimeSpan> timeToRun = new List<TimeSpan>();
public void OnStart(string[] args)
{
string timeToRunStr = "20:45;20:46;20:47;20:48;20:49";
var timeStrArray = timeToRunStr.Split(';');
CultureInfo provider = CultureInfo.InvariantCulture;
foreach (var strTime in timeStrArray)
{
timeToRun.Add(TimeSpan.ParseExact(strTime, "g", provider));
}
_timer = new System.Timers.Timer(60*100*1000);
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
ResetTimer();
}
void ResetTimer()
{
TimeSpan currentTime = DateTime.Now.TimeOfDay;
TimeSpan? nextRunTime = null;
foreach (TimeSpan runTime in timeToRun)
{
if (currentTime < runTime)
{
nextRunTime = runTime;
break;
}
}
if (!nextRunTime.HasValue)
{
nextRunTime = timeToRun[0].Add(new TimeSpan(24, 0, 0));
}
_timer.Interval = (nextRunTime.Value - currentTime).TotalMilliseconds;
_timer.Enabled = true;
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
_timer.Enabled = false;
Console.WriteLine("Hello at " + DateTime.Now.ToString());
ResetTimer();
}
Consider using Quartz.net and CronTrigger.
If u are clear abt what schedule it should run..then change time interval for timer in the timeelapsed event so that it runs according to schedule..i've never tried though
I would use a background thread and make it execute an infinite loop which does your work and sleeps for 15 minutes. It would be a lot cleaner and more simple for service code than using a timer.
See this article on MSDN.

how to have a function run inside a service every 10 minutes?

I have a windows service running, inside this i want to run a function every then minutes.
I have found some code but it doesn't seem to work?
I have a logger and it does not seem to go into the timer_Elapsed function ever?
protected override void OnStart(string[] args)
{
// SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
// test.Import();
log.Info("Info - Service Started");
_timer = new Timer(10 * 60 * 1000); // every 10 minutes??
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
log.Info("Info - Check time");
DateTime startAt = DateTime.Today.AddHours(9).AddMinutes(48);
if (_lastRun < startAt && DateTime.Now >= startAt)
{
// stop the timer
_timer.Stop();
try
{
log.Info("Info - Import");
SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
test.Import();
}
catch (Exception ex) {
log.Error("This is my error - ", ex);
}
_lastRun = DateTime.Now;
_timer.Start();
}
}
You need to start the timer:
protected override void OnStart(string[] args)
{
log.Info("Info - Service Started");
_timer = new Timer(10 * 60 * 1000); // every 10 minutes
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start(); // <- important
}
I don't see _timer.Start(), that should be your problem.
Daniel Hilgarth is correct - the main issue is that you never call Start on the timer.
That being said, you might want to also consider using the Windows Task Scheduler instead of a service with a timer. This allows you to schedule the task to run every 10 minutes, but also change the schedule whenever desired without a compilation change.
I need this functionality also. That is, my C# windows service must check email every 10 minutes. I stripped down some logic to make the code more effective, as follows :
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
_timer.Stop();
try
{
EventLog.WriteEntry(Program.EventLogName, "Checking emails " + _count++);
}
catch (Exception ex)
{
EventLog.WriteEntry(Program.EventLogName, "This is my error " + ex.Message);
}
_timer.Start();
}
The timer_elapsed method indeed will be call every 10 minutes, starting from the first _timer.start(), which you miss it by the way. I haven't done any checking of the _lastRun and startAt. I don't think we need it
Try starting the timer,
protected override void OnStart(string[] args)
{
// SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
// test.Import();
log.Info("Info - Service Started");
_timer = new Timer(10 * 60 * 1000); // every 10 minutes??
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start();
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
log.Info("Info - Check time");
DateTime startAt = DateTime.Today.AddHours(9).AddMinutes(48);
if (_lastRun < startAt && DateTime.Now >= startAt)
{
// stop the timer
_timer.Stop();
try
{
log.Info("Info - Import");
SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
test.Import();
}
catch (Exception ex) {
log.Error("This is my error - ", ex);
}
_lastRun = DateTime.Now;
_timer.Start();
}
}

how to have a service run at a specific time?

Ive got a service which currently i believe is running every 10 min, but i want it to run at 7pm every day, what do i need to change? ....
private Timer _timer;
private DateTime _lastRun = DateTime.Now;
protected override void OnStart(string[] args)
{
_timer = new Timer(10 * 60 * 1000); // every 10 minutes??
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (_lastRun.Date < DateTime.Now.Date)
{
// stop the timer
_timer.Stop();
try
{
SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
test.Import();
}
catch (Exception ex) { }
_lastRun = DateTime.Now;
_timer.Start();
}
}
Replacing:
if (_lastRun.Date < DateTime.Now.Date)
{
}
with:
DateTime startAt = DateTime.Today.AddHours(19);
if (_lastRun < startAt && DateTime.Now >= startAt)
{
}
will probably do the trick. But I would prefer to use a scheduled task as has been suggested already
Windows Service is a continuosly running task. If you are looking for something which needs to run at a Specified time, Write a Scheduled Task, Other good link.

Categories

Resources