basically I'm trying to implement the timer in class for my would-be very first game in C#; I want to use timers that will constantly update the player and provide certain periodic feedback, but I can't seem to get the 'timer' class to work correctly. If I use it in a loop (as shown below), it will wait 2 seconds, and then keep writing "You're Alive!" to the console with 0 delay in-between; and if I do not use the loop, the application just ends instantly.
using System;
using System.Timers;
public class MyClass
{
public static void myTimer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("You're alive!");
}
public static void Main(String[] args)
{
while (true)
{
Timer MyTimer = new Timer();
MyTimer.Interval = 2000;
MyTimer.Enabled = true;
MyTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
MyTimer.Start();
}
}
Just add below line after MyTimer.Start();
Console.ReadLine();
static void Main(String[] args)
{
Timer MyTimer = new Timer();
MyTimer.Interval = 2000;
MyTimer.Enabled = true;
MyTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
MyTimer.Start();
Console.ReadLine();
}
private static void myTimer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("You're alive!");
}
Related
In my program I need to generate an instance of a class which is "Vehicle", the Vehicle class has a timer within it, along with a boolean "vExists", when the timer hits an interval.
class VehicalGen
{
private Random rn1 = new Random();
private int agrotime;
private bool vExists;
//static AgrivationHandler agroTimeHandler;
private static Timer agroTimer = new Timer(100);
//agrotime: anywhere between 2 and 4 seconds (2000 to 4000)
///Generates the new Vehicles using GetCarType to change the outcome of the later variables
public VehicalGen()
{
this.vtype = RandomGeneration.GetCarType(rn1);
switch (this.vtype)
{
[....] //This is where the details of the vehicle are generated.
}
this.agrotime = RandomGeneration.GetRandomTime224(rn1);
this.vExists = true;
this.serviced = false;
//agroTimeHandler = new AgrivationHandler(agrotime);
agroTimer.Interval = agrotime;
agroTimer.Elapsed += AgroTimerElapsed;
agroTimer.Start();
}
public static void AgroTimerElapsed(object sender, ElapsedEventArgs e)
{
//here is where I need to set vExists to "False"
}
}
However I need to generate a specific instance of the class as far as I'm aware to do that, because it doesn't like "this.vExists = false", it just errors.
Yes is possible.
Try the following:
private void LoadTimer()
Timer timer = new Timer
timer.Interval = 4000;
timer.Enabled = true;
timer.Tick += new EventHandler(timer1_Tick);
timer.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
// do your boolean operation where
}
I've got this code in a Windows Service:
public void ConfigureService()
{
//timer = new Timer { Interval = 600000 };
timer = new Timer { Interval = 10000 };
// 10 minutes; 1 second while testing
timer.Elapsed += timer_Tick;
timer.Enabled = true;
RoboRprtrLib.WriteToLog("RoboRprtrService has started");
}
private void timer_Tick(object sender, ElapsedEventArgs eeargs)
{
timer.Elapsed -= timer_Tick;
try
{
RoboRprtrLib.WriteToLog("Timer has ticked");
RoboRprtrLib.GenerateAndEmailDueReports();
}
finally
{
timer.Elapsed += timer_Tick;
}
}
ConfigureService() is called from Program.cs:
static void Main()
{
// got this idea ("How to Debug or Test your Windows Service Without Installing it...") from http://www.codeproject.com/Tips/261190/How-to-Debug-or-Test-your-Windows-Service-Without
#if(!DEBUG)
var ServicesToRun = new ServiceBase[]
{
new RoboRprtrService()
};
ServiceBase.Run(ServicesToRun);
#else
var rrs = new RoboRprtrService();
rrs.ConfigureService();
#endif
}
I have a breakpoint in ConfigureService() on this line:
timer = new Timer { Interval = 10000 };
It is reached; I can step through the entire ConfigureService() method.
I have a breakpoint in the Elapsed/Tick event on the first line:
timer.Elapsed -= timer_Tick;
...and it is never reached.
Why not? Isn't the timer set to trip after 10 seconds, at which point the Tick event handler should be called?
UPDATE
This is the entire code for the class deriving from ServiceBase:
public partial class RoboRprtrService : ServiceBase
{
private Timer timer;
public RoboRprtrService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
ConfigureService();
}
public void ConfigureService()
{
//timer = new Timer { Interval = 600000 };
timer = new Timer { Interval = 50000 };
// 10 minutes; 50 seconds while testing
timer.Elapsed += timer_Tick;
timer.Enabled = true;
RoboRprtrLib.WriteToLog("RoboRprtrService has started");
}
private void timer_Tick(object sender, ElapsedEventArgs eeargs)
{
timer.Elapsed -= timer_Tick;
try
{
RoboRprtrLib.WriteToLog("Timer has ticked");
RoboRprtrLib.GenerateAndEmailDueReports();
}
finally
{
timer.Elapsed += timer_Tick;
}
}
protected override void OnStop()
{
timer.Enabled = false;
RoboRprtrLib.WriteToLog("RoboRprtrService has stopped");
}
}
UPDATE 2
It seems odd to me, but if I add this line:
RoboRprtrLib.GenerateAndEmailDueReports();
...to the end of the ConfigureService() method, the timer is eventually tripped.
UPDATE 3
More oddities: I was getting err msgs about needing to add the STAThread attribute (and a method was being called that shouldn't have been, which caused it to fail and the service to crash). So I decorated Main() in Program.cs with "[STAThread]" and now it works as it should.
The timer tripped several times during the operation, but I have code to exit if processing is occurring. When the called method completed, the IDE "flashed" as if to say, "Poof! I'm outta here!"
So my Program.cs code is now:
[STAThread]
static void Main()
{
#if(!DEBUG)
var ServicesToRun = new ServiceBase[]
{
new RoboRprtrService()
};
ServiceBase.Run(ServicesToRun);
#else
var rrs = new RoboRprtrService();
rrs.ConfigureService();
Console.ReadLine();
#endif
}
...and the most pertinent code in the class that derives from ServiceBase is:
public void ConfigureService()
{
//timer = new Timer { Interval = 600000 };
timer = new Timer { Interval = 50000 };
// 10 minutes; 50 seconds while testing
timer.Elapsed += timer_Tick;
timer.Enabled = true;
RoboRprtrLib.WriteToLog("RoboRprtrService has started");
operationIsRunning = true;
RoboRprtrLib.GenerateAndEmailDueReports();
operationIsRunning = false;
}
private void timer_Tick(object sender, ElapsedEventArgs eeargs)
{
if (operationIsRunning) return;
operationIsRunning = true;
. . .
The "if (operationIsRunning) return;" breakpoint in the tick handler was reached three times during my last run while GenerateAndEmailDueReports() was executing, and each time it, as designed, returned.
As Hans Passant said in comments, in debug mode you code will terminate immediately after calling ConfigureService, so there is no time for the timer to be executed.
In release mode ServiceBase.Run blocks the thread until the service has finished, but this doesn't happen in debug version.
EDIT:
Actually I tried with Console.ReadLine() and did not stop, apparently standard input is redirected, just try to keep the process running, with an infinite loop or something.
Like this:
static void Main()
{
// got this idea ("How to Debug or Test your Windows Service Without Installing it...") from http://www.codeproject.com/Tips/261190/How-to-Debug-or-Test-your-Windows-Service-Without
#if(!DEBUG)
var ServicesToRun = new ServiceBase[]
{
new RoboRprtrService()
};
ServiceBase.Run(ServicesToRun);
#else
var rrs = new RoboRprtrService();
rrs.ConfigureService();
while (true)
Thread.Sleep(100);
#endif
}
I have some timers that are updating a DataSet. I need the timers to run sequentially without bumping into each one after the other. I might be running only one or two or three at the same time. So the idea is they have to run 1,2,3 and then again 1,2,3. I created this fiddle but I don't have it down yet:
class Example
{
private static ManualResetEvent mr = new ManualResetEvent(false);
private static AutoResetEvent event_1 = new AutoResetEvent(true);
private static AutoResetEvent event_2 = new AutoResetEvent(false);
private static void t1_Tick(object sender, EventArgs e)
{
//update ds inside here
//ds.Tables["Alarms"].Rows[0][0]="foo";
//same in all other Tick functions
Console.WriteLine("1");
mr.Set();
}
private static void t2_Tick(object sender, EventArgs e)
{
mr.WaitOne();
Console.WriteLine("2");
mr.Set();
}
private static void t3_Tick(object sender, EventArgs e)
{
mr.WaitOne();
Console.WriteLine("3");
mr.Set();
}
static void Main()
{
System.Timers.Timer t1 = new System.Timers.Timer();
t1.Elapsed += t1_Tick;
t1.Enabled = true;
System.Timers.Timer t2 = new System.Timers.Timer();
t2.Elapsed += t2_Tick;
t2.Enabled = true;
System.Timers.Timer t3 = new System.Timers.Timer();
t1.Elapsed += t1_Tick;
t1.Enabled = true;
Console.ReadKey();
}
}
If there are only two timers running it would have to be 1,2 an then again 1,2
Could you use a thread-safe DispatcherTimer instead?
See http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchertimer.aspx
I have four buttons that are called "ship1,ship2" etc.
I want them to move to the right side of the form (at the same speed and starting at the same time), and every time I click in one "ship", all the ships should stop.
I know that I need to use a timer (I have the code written that uses threading, but it gives me troubles when stopping the ships.) I don't know how to use timers.
I tried to read the timer info in MDSN but I didn't understand it.
So u can help me?
HERES the code using threading.
I don't want to use it. I need to use a TIMER! (I posted it here because it doesnt give me to post without any code
private bool flag = false;
Thread thr;
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
flag = false;
thr = new Thread(Go);
thr.Start();
}
private delegate void moveBd(Button btn);
void moveButton(Button btn)
{
int x = btn.Location.X;
int y = btn.Location.Y;
btn.Location = new Point(x + 1, y);
}
private void Go()
{
while (((ship1.Location.X + ship1.Size.Width) < this.Size.Width)&&(flag==false))
{
Invoke(new moveBd(moveButton), ship1);
Thread.Sleep(10);
}
MessageBox.Show("U LOOSE");
}
private void button1_Click(object sender, EventArgs e)
{
flag = true;
}
Have you googled Windows.Forms.Timer?
You can start a timer via:
Timer timer = new Timer();
timer.Interval = 1000; //one second
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled = true;
timer.Start();
You'll need an event handler to handle the Elapsed event which is where you'll put the code to handle moving the 'Button':
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
MoveButton();
}
Basically i have a problem with this timer program I am trying to put together. On starting the program it will utilise a steady 25% CPU which i dont mind, but every time the timer fires it adds another 25% on to the CPU so on the 4th pass im completely maxed out.
I take it I'm not disposing of the timer correctly after it has fired but im new to c# and not really sure how to go about this.
the cope of my program is basically:
Execute some procedures - once completed start timer
Wait until timer elapses then start procedures again, disabling the timer until completed
any help would be greatly appreciated :)
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
IpCheck();
}
private static void EnableTimer()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
// Set the Interval to x seconds.
aTimer.Interval = 10000;
aTimer.Enabled=true;
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = false;
aTimer.Dispose();
}
ok revised version below - simplified and ruled out the ip check so all it does now is show a message box - this will not even execute anymore :(
public class Timer1
{
System.Timers.Timer aTimer = new System.Timers.Timer();
public static void Main()
{
Timer1 tTimer = new Timer1();
tTimer.EnableTimer();
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
aTimer.Enabled = false;
MessageBoxPrint();
aTimer.Enabled = true;
}
private void EnableTimer()
{
// Set the Interval to x seconds.
aTimer.Interval = 10000;
aTimer.Enabled=true;
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
}
public static void MessageBoxPrint()
{
MessageBox.Show("Testing");
}
}
You're probably looking for something like this:
private static System.Timers.Timer aTimer = new System.Timers.Timer();
// This method will be called at the interval specified in EnableTimer
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
aTimer.Enabled = false; // stop timer
IpCheck();
aTimer.Enabled = true; // restart timer so this method will be called in X secs
}
private static void EnableTimer()
{
// Set the Interval to x seconds.
aTimer.Interval = 10000;
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled=true; // actually starts timer
}
I don't quit get, why you have the cpu load, but I would do:
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
((Timer)source).Enabled = false;
IpCheck();
((Timer)source).Enabled = true;
}
and don't dispose the timer in the method call.
The problem is that he is creating a Timer1 inside the Timer1 class so when you load Timer1, it loads another Timer1 which loads another timer1 which loads.... It think you get it
public class Timer1
{
System.Timers.Timer aTimer = new System.Timers.Timer();
public static void Main()
{
Timer1 tTimer = new Timer1();//<-this line right here is killing you
//remove it, as I don't see anyuse for it at all
then in this line
tTimer.EnableTimer();
just say
EnableTimer();
//or
this.EnableTimer();
You don't need to instantiate the class you are working in, as far as it is concerned it is already instantiated.
static System.Timers.Timer aTimer = new System.Timers.Timer();
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
aTimer.Enabled=false;
IpCheck();
aTimer.Enabled=true;
}
private static void EnableTimer()
{
// Set the Interval to x seconds.
aTimer.Interval = 10000;
aTimer.Enabled=true;
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
}
private static void DisableTimer()
{
aTimer.Elapsed -= new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = false;
}
NOT TESTED NOT COMPILED, just a sample what i would do in your place, all the added lines are there without no tabs