No overload for 'mysql' matches delegate 'ElapsedEventHandler'. Windows Service C# - c#

I have developed a windows service for copying a file from one location to another.
Since I need to run the service in the background there is a necessity of implementing a timer function.
Service.cs
protected override void OnStart(string[] args)
{
//OnStart(new string[0]);
}
public void Start()
{
timer1 = new Timer();
this.timer1.Interval = 30000; //every 30 seconds
41 ***this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.mysql);***
timer1.Enabled = true;
43 mysql();
}
static void mysql()
{
**File copy code included in this function.
}
The error triggers in line 41 mentioned above and is,
No overload for 'mysql' matches delegate 'ElapsedEventHandler'.

set param on mysql() like this
static void mysql(object sender, ElapsedEventArgs e)
I hope it works for you :)
++ added via comment
this code will allows timer work with interval
add this code in Start()
this.timer1.Interval = 1000;
this.timer1.Tick += new System.EventHandler(this.mysql_tick);
and add this code out of Start()
private void mysql_tick( object sender, EventArgs e ){
blah blah... }
++ after that you need to use timer1.Start(); for work with mysql_tick
++ timer1.Stop(); will halt work.

Related

Timer error after couple minutes running C#

I'm pretty new in c# and I'm programing just for my personal studies, I have been trying to program an instruction where a read some data from a remote station to my application (m64...mw74), it's running OK for couple minutes but its crash maybe after 5 minutes.
please see the code I'm using below to update my data every 1 second and write it in a simple text box in my form.enter image description here
Thank you very much in advance.
private void Load_act()
{
actvalueL1.Text = plc.Read("mw64").ToString();
actvaluep1.Text = plc.Read("mw68").ToString();
actvaluep2.Text = plc.Read("mw71").ToString();
actvaluep3.Text = plc.Read("mw74").ToString();
InitTimer();
}
private Timer timer1;
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000; // in miliseconds
timer1.Start();
//Console.ReadLine();
}
private void timer1_Tick(object sender, EventArgs e)
{
Load_act();
}
You're chaining the timers, eventually going to run yourself out of memory as they cannot dispose - the timer creates the next with its own call. Return them on to a parent method that loops your timer 'initTimer'

Unable to pass custom method to ElapsedEventHandler() as an argument

I am working on a windows service which will look for backup files in a particular folder. When it finds one the service will move all the backup files from that location and move them to an archived folder.
I have used FileSystemWatcher before but since it doesn't work on Servers I am using DirectoryInfo to look for the files.
The requirement is to run this service at every 5 minutes interval to look for any new backup files coming in.
I am stuck with the timer implementation.
Following is my code:
I want to call MoveToProcessed(processed) method from the ElapsedEventHandler. but I am getting error CS0149 - Method name expected.
protected override void OnStart(string[] args)
{
DirectoryInfo dir = new DirectoryInfo(backupdirectory);
// Other unrelated code omitted
// Move all the Backup files to Processed folder at certain intervals.
createOrderTimer = new System.Timers.Timer();
//***** ERROR ON THE FOLLOWING LINE *****
createOrderTimer.Elapsed += new ElapsedEventHandler(MoveToProcessed(processed));
//***************************************
createOrderTimer.Interval = 300000; // 15 min
createOrderTimer.Enabled = true;
createOrderTimer.AutoReset = true;
createOrderTimer.Start();
}
private void MoveToProcessed(string processed)
{
// Code here backs up and restores files
}
You can easily call a method from an event handler, but the event handler method itself must match a specific signature. For the System.Timers class, it should look something like this:
private static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
So you can simply create a method with this signature, assign it as an event handler, and then call your method from there:
// Elapsed event handler calls our other method
private static void CreateOrderTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// Not sure what the string argument represents, or how it should be set
MoveToProcessed("some string");
}
// We can assign the event handler above when creating the Timer:
protected override void OnStart(string[] args)
{
var createOrderTimer = new System.Timers.Timer
{
Interval = TimeSpan.FromMinutes(15).TotalMilliseconds,
AutoReset = true
};
createOrderTimer.Elapsed += CreateOrderTimer_Elapsed;
createOrderTimer.Start();
}

How to start method on timer from windows service?

I have a method that executes in about 10 minutes. And it goes well just by itself. I need to start this method every hour using windows service (this is obligatory). So I've written my service by some examples (just one invoke for start):
partial class ServiceWSDRun : ServiceBase
{
protected override void OnStart(string[] args)
{
Thread t = new Thread(WebServiceDownload.MainProgram.Execute);
t.Start();
}
}
Now when I install it, it launches my method in a new thread but this thread seem to end with the OnStart() - it actually logs some info from the beginning of me method. Why does it stop and what should I do?
And I'm thinking in the end I should have something like this:
partial class ServiceWSDRun : ServiceBase
{
System.Timers.Timer timer = null;
protected override void OnStart(string[] args)
{
Thread t = new Thread(WebServiceDownload.MainProgram.Execute);
t.Start();
timer = new System.Timers.Timer();
timer.Interval = 60 * 60 * 1000; // 1 hour
timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimer);
timer.Enabled = true;
}
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
{
WebServiceDownload.MainProgram.Execute();
}
protected override void OnStop()
{
timer.Enabled = false;
}
}
How do I make it work? And keep in mind that method takes ~10 mins to execute.
You should use System.Threading.Timer instead of System.Timers.Timer.
Here is the reference for this:
https://msdn.microsoft.com/en-us/library/system.threading.timer(v=vs.110).aspx
Also, another thread about the same topic:
System.Timers.Timer vs System.Threading.Timer
You should lock the execution, avoiding the second execution before the first one finishes.

How to use properly Timer Object?

I have this code behind in asp.net page:
protected void LoadFile(object sender, EventArgs e)
{
try
{
Timer myTimer = new Timer();
myTimer.Elapsed += new ElapsedEventHandler( RemoveFile );
myTimer.Interval = 60000;
myTimer.Start();
}
catch (Exception)
{
}
}
private void RemoveFile(object source, ElapsedEventArgs e)
{
string path = UniquePath();
File.Delete(path);
}
When LoadFile event handler fired the RemoveFile function fired after 60 sec(as defined in this row myTimer.Interval = 60000), if LoadFile fired again after 40 seconds the RemoveFile will fire in 20 seconds.
My question is how to make the RemoveFile function to be activated after 60 seconds from last call of the LoadFile event hanlder?
May be you could use
myTimer.Stop(); just after Timer myTimer = new Timer();
I would use Microsoft's Reactive Extensions (NuGet "Rx-Main") for this. The code becomes:
private SerialDisposable _serialDisposable = new SerialDisposable();
protected void LoadFile(object sender, EventArgs e)
{
_serialDisposable.Disposable =
Observable
.Interval(TimeSpan.FromSeconds(60.0))
.Subscribe(n =>
{
string path = UniquePath();
File.Delete(path)
});
}
Now, observables are like events and calling .Subscribe is like attaching to an event. The .Subscribe call returns an IDisposable which you can use to detach from the observable by calling .Dispose(). The SerialDisposable object is a special disposable class provided by Rx that lets you assign new disposables and automatically dispose any previously assigned disposables. This automatically resets the timer every time LoadFile is run.
This is just one use of Rx - it has so many more uses and is very powerful and worth learning.

Pausing appending of Text for a certain number of milliseconds

I'm currently making a text based game, but I need the calls to pause for a certain number of milliseconds. I'm looking for something like this:
void InitProgram()
{
WriteToText("Welcome!");
CreatePause(3000); // Pause execution HERE for 3 seconds without locking UI
WriteToText("How are you?"); // Continue
StartTutorial();
}
So like, the method will be called, do its waiting thing, and then return. And when it returns, normal execution is continued.
What can I do for this effect?
You could use a timer:
readonly Timer _timer = new Timer();
void InitProgram()
{
WriteToText("Welcome!");
_timer.Interval = 3000;
_timer.Tick += timer_Tick;
_timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
WriteToText("How are you?"); // Continue
StartTutorial();
_timer.Stop();
}
If you wanted to call this multiple times, just put _timer.Start into it's own method, every time you call it, 3 seconds later whatever is in timer_Tick will happen:
private void StartTimer()
{
_timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
WriteToText("How are you?"); // Continue
StartTutorial();
_timer.Stop();
}
If target framework is 4.0 or higher and IDE is VS2012 or higher, then you can use async/await
private async void Foo()
{
Console.WriteLine("Going to Await");
await Task.Delay(5000);
Console.WriteLine("Done with awaiting");
}
It's pretty simple and straightforward and the biggest advantage is, that your "linear" flow is kept, because the necessary callbacks etc are handled by the compiler automatically.
How about something like this?
Its all pseudo code, I have not tested...
Thread _thread;
void InitProgram()
{
WriteToText("Welcome!");
ThreadStart ts = new ThreadStart(StartThread);
_thread = new Thread(ts);
_thread.Start();
}
private void StartThread()
{
Thread.CurrentThread.Sleep(3000);
this.Invoke(delegate { this.StartTutorial(); });
}
private void StartTutorial()
{
WriteToText("How are you?"); // Continue
//Start tutorial
}
Hahahahhaha! I figured out the answer using possibly the most crazy method available! Check this out, guys!
First, declare global List:
private List<Action> actionList = new List<Action>();
Now, this is what you do in the method you wish to call wait from:
WriteToLog("Hello!");
Action act = delegate() { WriteToLog("How are you?"); }; actionList.Add(act); // Create a new Action out of this method and add it to the action list!
CreatePause(3000); // Call the method with your specified time
void CreatePause(int millisecondsToPause)
{
Action w = delegate() { Thread.Sleep(millisecondsToPause); };
for (int i = 0; i < actionList.Count; i++) // Iterate through each method in the action list that requires attention
{
Action a_Instance = (Action)actionList[i]; // Add a cast to each iteration
AsyncCallback cb = delegate(IAsyncResult ar) { Invoke(a_Instance); w.EndInvoke(ar); }; // Do each method!!!!
w.BeginInvoke(cb, null);
}
actionList.Clear(); // Clear that list!
return; // Return!
}
To be honest, this shouldn't work, but it does.

Categories