EDIT: I shortened the code example
I am coding in C#, trying to set up a timer.
I have done it before but this time it is not working at all.
I have looked through it countless times and cannot find whats wrong!
Please help!
The timer should start in the RestoreMana() method but it doesn't seem to.
The timer should then run restoreTimer_Elapsed() every one second (1000 milliseconds).
This also doesn't seem to be the case.
This code is for a Terraria TShock Plugin and uses packages from it, but the timer is from System.Timers. So can anyone please help? :D
Thanks!
ALT Pastebin link: http://pastebin.com/WU7j3aqe
//'Import' necessary packages
using System;
using TShockAPI;
using Terraria;
using TerrariaApi.Server;
using System.Timers;
namespace Restore
{
//Variables
private Timer restoreTimer = new Timer(1000);
public override void Initialize()
{
//Calls CallRestore() when /restore is typed
Commands.ChatCommands.Add(new Command("fmg.restore", CallRestore, "restore"));
//Setup the Timer
restoreTimer.Elapsed += new ElapsedEventHandler(restoreTimer_Elapsed);
restoreTimer.Interval = 1000;
restoreTimer.AutoReset = true;
restoreTimer.Enabled = false;
}
//There would usually be more code here but I shortened it
private void CallRestore(CommandArgs args)
{
RestoreMana(args);
}
//This doesn't get run
private void restoreTimer_Elapsed(object sender, ElapsedEventArgs e)
{
player.SendMessage("Timer", Color.Aqua);
}
//Starts restoreTimer
private void RestoreMana(CommandArgs args)
{
restoreTimer.Start();
}
}
}
NB: I hope you figured the issue now as you asked this about 1 month ago.
Anyway, as stated in the comments, I would say your problem seems to lie on this line:
restoreTimer.Enabled = false;
should rather be:
restoreTimer.Enabled = true;
... unless you're setting this boolean elsewhere before your call to restoreTimer.Start();
Related
I need a timer that executes every minute but i have trouble getting the timer to run at all with code that i used before. so i guess i am doing sth fundamentally wrong that is not code related but even in a just newly created Console project in visual studio community 2017 it doesn't execute the _timer_elapsed method. the console terminates immediately without errors as if it has executed every code
using System;
using System.Timers;
namespace Test
{
class Program
{
static Timer _timer;
public static void Main(string[] args)
{
var timer = new Timer(60000);
timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
timer.Enabled = true;
_timer = timer;
}
static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("test");
}
}
}
what am I missing here?
You need your program to stay alive, rather than return from Main. An quick and easy way to do this is to wait for some input at the end:
public static void Main(string[] args)
{
var timer = new Timer(60000);
timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
timer.Enabled = true;
_timer = timer;
Console.ReadLine();
}
There is no such thing as a bad question.
(Though some questions show more affinity with programming, and some show less.)
If you look at your code, your main sets up a timer and then proceeds to terminate. So, of course your program exits immediately and the timer is never fired.
In order to see your timer firing, your program will need to keep running for at least as long as one period of your timer.
in a company I'm working we want to build an automation tool that should run a script written in text. I'm new to timers, and what I want to do is to make a foreach (not a must) that will run line after line in the script and call a parser for later use.
What I want is something like this:
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
foreach (ScriptCell CELL in ScriptList)
{
//fire the method when time is up
aTimer.Elapsed += new ElapsedEventHandler(DoScriptCommand(CELL.CellText));
}
I know what I wrote doesnt make allot of sense , but I'm a BIT clueless here
PS. I was looking in other topics before posting this Q , but I didnt find nothing that seems to fill the gap
The introduction of await makes acting on each item in a sequence, while waiting for a period of time between each item, very easy:
foreach(var cell in ScriptList)
{
DoScriptCommand(cell.CellText)
await Task.Delay(TimeSpan.FromSeconds(2));
}
Do this IN the elapsed event, not a new handler for each line (otherwise they'll be executed in a parallel manner)
aTimer.Elapsed += new ElapsedEventHandler((sender, args) =>
{
foreach (ScriptCell CELL in ScriptList)
{
DoScriptCommand(CELL.CellText);
}
}
If you are simply looking at running a script or scripts on a regular basis I would search "cron" if you are using a Unix/Linux machine or "Windows Task Scheduler" if you are using a windows machine. Each of these tools lets you specify a path to a script, the interval they should run, what command line parameters to use etc.
I did little tetris in my application.
I used timer for this code: I hope it will help you.
İf you dont use thread, your program will stuck while timer is running
so i used thread like this:
private void ciz()
{
int beklemeSuresi = 1000;//1000 = 1sec
for (int i = 0; i < 15; i++)
{
if (g != null)
{
g.Clear(Color.AliceBlue);
}
solLCiz(100, 100 + i * 20, yon);
Application.DoEvents();
Thread.Sleep(beklemeSuresi);
}
}
Of course you must begin thread at beginning of program like this:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
ciz();
}
private void Form1_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
I am working with socket programing ,I can to check the live connection of Users after some time intervals such as 10 seconds.But currently, i have no idea. how i will do it.
Please help me. I shall be highly thankful.
From MSDN Timer Class (System Timers):
Below is an example from the MSDN page
[C#]
public class Timer1
{
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 10 seconds.
aTimer.Interval=10000;
aTimer.Enabled=true;
Console.WriteLine("Press \'q\' to quit the sample.");
while(Console.Read()!='q');
}
// Specify what you want to happen when the Elapsed event is raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("Hello World!");
}
}
Include: using System.Threading;
I have no idea what you are doing (have code to show us?), but here's the general logic:
while (/*connection is active*/)
{
//check connection
Thread.Sleep(10000); //10 seconds
}
It really depends on what your doing, and how you are checking for the connection.
You can use the Threading.sleep(); a timer, or depending on what your doing you might be able to use an event handler based off of connects / disconnects...
I am trying to have a Windows service run all the time in the background of my computer with no-one knowing. My Windows service downloads the content of my email inbox and puts it in my database.
My Windows service just seams to stop - it enters a log every 60 seconds and then stops about 10 mins in?
I have posted my code below. Can any one see or tell me a reason why?
Any help would be much appreciated.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
namespace EmailWindowsService
{
public partial class MyEmailService : ServiceBase
{
private DateTime lastRun;
private bool flag = true;
private static System.Timers.Timer aTimer;
public MyEmailService()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MySource")) // every thing the windows service does is logged in server explorer
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource", "MyNewLog");
}
eventLogEmail.Source = "MySource";
eventLogEmail.Log = "MyNewLog";
// Timer Code
aTimer = new System.Timers.Timer(1 * 60 * 1000); // 60 seconds
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true;
// Timer Code
}
protected override void OnStart(string[] args)
{
flag = true;
lastRun = DateTime.Now;
eventLogEmail.WriteEntry("Started");
}
protected override void OnStop()
{
eventLogEmail.WriteEntry("Stopped");
}
protected override void OnPause()
{
eventLogEmail.WriteEntry("Paused");
}
protected override void OnContinue()
{
eventLogEmail.WriteEntry("Continuing");
}
protected override void OnShutdown()
{
eventLogEmail.WriteEntry("ShutDowned");
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
RetriveEmailClass Emails = new RetriveEmailClass();
if (flag == true)
{
eventLogEmail.WriteEntry("In getting Email Method");
Emails.ServiceEmailMethod();
lastRun = DateTime.Now;
flag = false;
}
else if (flag == false)
{
if (lastRun.Date < DateTime.Now.Date)
{
Emails.ServiceEmailMethod();
eventLogEmail.WriteEntry("In getting Email Method");
}
}
}
}
}
See that your class has no errors, an error there could throw you whole service out.
Also try putting your timer into a method and only call it, not have it in your service code.
A windows service should always be made as an empty shell that just call's methods.
Couple of reasons that your Windows services stops running.
1. Unhandled exception in your code. Looking from you code snippet, please add exception handling in the OnTimedEvent() method.
2. You service may crashed for some reason. In this case, you can go to event viewer to find out the reason for the failure.
Hope this helps.
You most likely have an unhandled exception. It's hidden since you use System.Timers.Timer. That timer eats all unhandled exceptions instead of letting them crash your app.
That means that your app might look like it's running OK while it's not. A try/catch in the timer callback will prove that.
I do recommend that you use System.Threading.Timer instead since it do not work in that way.
Your code is straightforward enough except the source for your Emails.ServiceEmailMethod method. Does the method generate any exceptions? If so, they have not been trapped in your timer method. Try:
try { Emails.ServiceEmailMethod(); }
catch (Exception ex) { eventLogEmail.WriteEntry(ex.Message); }
i have a problem with a application. this application simply shows a number value every second. you can see it as a countdown. the problem is, that this Timer sometimes stop to tick and i dont know why. where is my code:
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
i start the timer afte the Loaded event:
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
Timer t1 = new Timer(TimerCall);
t1.Change(0, 1000);
}
and here is the method which chanes the text:
private void TimerCall(object state)
{
TextField.Dispatcher.BeginInvoke(delegate
{
TextField.Text = "some text change";
});
}
I dont understand why this sometimes stops
Have a look at this article especially the section on The Tombstone
Next to the fact that the Timer is a local variable instead of a class member, you might be running into the tomb stoning process. The article explains this quite well.