Converting C# System.Timer to Threading.Timer - c#

i have been using System.Timer to run a windows service but have come across the problem where the timer randomly doesnt fire. I checked it yesterday and it hadnt fired for over 2 hours when its meant to fire every 10 mins. I read this up on Google and apparently its a known problem, the answer being to change over to Threading.Timer. I havent used this before so was looking for some insight. My current code is as follows:
using System;
using System.Timers;
using System.ServiceProcess;
namespace Code
{
public partial class Service : ServiceBase
{
Timer timer = new Timer();
public Service()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 10000;
timer.Enabled = true;
}
protected override void OnStop()
{
timer.Enabled = false;
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
timer.Enabled = false;
// Run system code here
timer.Interval = 600000;
timer.Enabled = true;
}
}
}
Basically, this normally works fine. The system starts the timer and fires after 10 seconds. It stops the timer, does the job, resets the timer for 10 minutes and enables it. For the most part this always works, but as mentioned randomly decides to stop working, probably due to system resources etc.
If anyone can help me convert this into a Threading.Timer it would be appreciated.
Thanks,
Chris

Here's my best guess - not got time to test it, sorry :(
using System;
using System.Threading;
using System.ServiceProcess;
namespace Code
{
public partial class Service : ServiceBase
{
Timer timer;
AutoResetEvent autoEvent;
bool stopped = true;
public Service()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
stopped = false;
TimerCallback tcb = new TimerCallback(OnElapsedTime);
timer = new Timer(tcb, null, 10000, 600000);
}
protected override void OnStop()
{
stopped = true;
timer.Dispose();
}
private void OnElapsedTime(Object stateInfo)
{
if (stopped)
return;
// Run system code here
}
}
}

http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx
Scroll down to find the example.

Related

Error 1053: Service did not respond in time

I created a new Windows-Service project and added it to the services using sc.exe, but I am always getting the error when I try to execute the Service.
Code in Program:
static void Main() {
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
Code in ServiceBase:
public Service1() {
InitializeComponent();
}
protected override void OnStart(string[] args) {
while(true) {
Console.WriteLine("Message all 5 sec...");
Thread.Sleep(5000);
}
}
protected override void OnStop() {
Environment.Exit(0);
}
I tried extending the Timeout in Registry(ServicesPipeTimeout), Using Threads and owning the Service but i still get the error.
Any Help is appreciated.
Kind Regards
Your service will never get out of the onStart-callback because of the endless loop you have created there. So this is blocking and will never finish.
You need to use a timer for your use-case. Just start a timer in your OnStart method and it shall run as expected:
public Service1() {
InitializeComponent();
}
public OnStart(string[] args)
{
Timer timer = new Timer();
timer.Interval = 5000; // 5 seconds
timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
timer.Start();
}
public void OnTimer(object sender, ElapsedEventArgs args)
{
Console.WriteLine("Message all 5 sec...");
}
The timer will send an event every 5 seconds and the added ElapsedEventHandler will call your OnTimer-Method.

WCF (Can't add Quartz in WCF Project)

(As I'm new to WCF)
I want to add Quartz in Windows Communication Foundation (WCF) project.
And I also wants to know that which file or method execute first after run the application.
Instead of using Quartz, I used C# Timer.
The Timer class in C# represents a Timer control that executes a code block at a specified interval of time repeatedly.
//Timer Class
public class FileJob
{
private System.Timers.Timer ProcessTimer;
public void Start()
{
try
{
ProcessTimer = new System.Timers.Timer();
ProcessTimer.AutoReset = true;
ProcessTimer.Elapsed += new System.Timers.ElapsedEventHandler(ProcessTimer_Elapsed);
ProcessTimer.Interval = 300000; //5 minutes
ProcessTimer.Start();
}
catch (Exception ex)
{ }
}
private void ProcessTimer_Elapsed(object sender, EventArgs e)
{
UploadFile();
}
}
Global.asax.cs
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
FileJob obj = new FileJob();
obj.Start();
}
}

Run loop outside onStart

I'm making a service in C#.
I have the functions:
onStart();
copy();
onStop();
I was running copy() inside the onStart() function. But it was making the service status be set to starting forever, since the copy() function is a loop that runs infinitely (with a Thread.Sleep() inside), making the service unstoppable, unless I finish the proccess in Task Manager.
So, question is:
How can I get copy() to run at the end of onStart() and get onStart() not to wait for the completion of copy()?
You can start new Thread from OnStart so that your service return control back service controller.
protected override void OnStart(string[] args)
{
Thread MyThread = new Thread(new ThreadStart(Starter));
MyThread.Start();
base.OnStart(args);
}
private void Starter()
{
//Add your long running code here
}
You can also use Timer that will be started in OnStart and will keep your service running.
private System.Timers.Timer timer;
protected override void OnStart(string[] args)
{
this.timer = new System.Timers.Timer(3000); // 30000 milliseconds = 30 seconds
this.timer.AutoReset = true;
this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
this.timer.Start();
}
protected override void OnStop()
{
this.timer.Stop();
this.timer = null;
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//Your code goes here
}
You can use a new Thread or use a Timer, with the code of an iteration in the Tick event.

Calling method at the start of windows service in c#

Please look at this piece of code
public partial class TestService : ServiceBase
{
private static System.Timers.Timer aTimer;
protected override void OnStart(string[] args)
{
aTimer = new Timer(10000 * 6 * 5); // 5 minutes interval
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
......
}
}
When I start this service at say 4:00 pm, the first time OnTimedEvent is called is at 4:05 pm, then 4:10 pm and so on. I would like the OnTimedEvent to be called at 4:00 pm as soon as I start the service. Is there anything I am missing here?
Use a System.Threading.Timer rather than a System.Timers.Timer.
It has a constructor overload that in addition to specifying the interval allows you choose the start delay, which can be set to 0 to fire immediately.
For a Comparison of the timer classes, see Windows.Forms.Timer OR System.Threading.Timer (specifically 'Initial timer event schedulable?')
You could just call the event in the OnStart
OnTimedEvent(this, null)
System.Timers.Timer starts counting down from 5 minutes and then the event is triggered. So it won't be able to trigger and run the code till the timer reaches 0.
The code may be run before the event listener is enabled this way shown below:
public partial class TestService : ServiceBase
{
private static System.Timers.Timer aTimer;
protected override void OnStart(string[] args)
{
aTimer = new Timer(10000 * 6 * 5); // 5 minutes interval
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
foo();
aTimer.Enabled = true;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
foo();
}
private void foo(){
.....
}
}

Event Handler Problem in Windows Service

I am going nuts. I can't figure out the problem.
I have a windows service that has a simple timer method. If I start the service, it always gives out exception at onTimerElapsed event. But If I write my XMLOperation methods in a different method(but not timer which I only need) and call it from program.cs, it works just fine. The working code is at the bottom also.
partial class DatabaseService : ServiceBase
{
Timer timer = new Timer();
public DatabaseService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer.Interval = 10000;
timer.Enabled = true;
timer.Elapsed += new ElapsedEventHandler(onElapsedTime);
timer.Start();
}
protected override void OnStop()
{
timer.Enabled = false;
}
public void onElapsedTime(object source, ElapsedEventArgs e)
{
try
{
XMLOperations operation = new XMLOperations();
operation.WebServiceFlexiCampaigns("http://www.flexi.com.tr/data/xml/pazaryeri/mobil.xml");
operation.WebServiceShopMilesCampaignsXMLRead("http://www.shopandmiles.com/xml/3_119_3.xml");
operation.WebServiceBonusCampaignsXMLRead("http://www.bonus.com.tr/apps/getcampaignxml.aspx?type=campaigns");
}
catch (Exception ex)
{
StreamWriter SW;
SW = File.CreateText("c:\\1.txt");
SW.WriteLine(ex.Message);
SW.Close();
}
}
here is the working one, but this time I could not manage to work that code in periods of time like I can do in timer event. I call test method manually from program.cs
partial class DatabaseService : ServiceBase
{
Timer timer = new Timer();
public DatabaseService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer.Interval = 10000;
timer.Enabled = true;
timer.Elapsed += new ElapsedEventHandler(onElapsedTime);
timer.Start();
}
protected override void OnStop()
{
timer.Enabled = false;
}
public void test()
{
try
{
XMLOperations operation = new XMLOperations();
operation.WebServiceFlexiCampaigns("http://www.flexi.com.tr/data/xml/pazaryeri/mobil.xml");
operation.WebServiceShopMilesCampaignsXMLRead("http://www.shopandmiles.com/xml/3_119_3.xml");
operation.WebServiceBonusCampaignsXMLRead("http://www.bonus.com.tr/apps/getcampaignxml.aspx?type=campaigns");
}
catch (Exception ex)
{
StreamWriter SW;
SW = File.CreateText("c:\\1111.txt");
SW.WriteLine(ex.Message);
SW.Close();
}
}
You can try this thread (see SamAgain response):
http://social.msdn.microsoft.com/Forums/en/clr/thread/8fbca78b-5078-4a12-8abb-4051076febbb
Hope it will work.

Categories

Resources