I would like to know how to run a c# program in background every five minute increments. The code below is not what I would like to run as a background process but would like to find out the best possible method to do this using this code so that I can implement it on another code. so this process should run after a five minute increment. I know I could use threads to do so, but dont really now how to implement this. I know this is the best way How to run a console application on system Startup , without appearing it on display(background process)? this to run in the background, but how would I have the code running in five minute increments
class Program
{
static void Main(string[] args)
{
Console.Write("hellow world");
Console.ReadLine();
}
}
This app should run continuously, putting out a message every 5 minutes.
Isn't that what you want?
class Program
{
static void Main(string[] args)
{
while (true) {
Console.Write("hellow world");
System.Threading.Thread.Sleep(1000 * 60 * 5); // Sleep for 5 minutes
}
}
}
Why not just use Windows Task Scheduler?
Set it to run your app at the desired interval. It's perfect for this sort of job and you don't have to mess about with forcing threads to sleep which can create more problems that it solves.
How about using a System.Windows.Threading.DispatcherTimer?
class Program
{
static void Main(string[] args)
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 5, 0); // sets it to 5 minutes
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
static void timer_Tick(object sender, EventArgs e)
{
// whatever you want to happen every 5 minutes
}
}
Probably the simplest way to "fire" a new process every X minutes is to use Windows Task Scheduler.
You could of course do something similar programmatically, e.g. create your own service, that starts the console application every X minutes.
All this under assumption you actually want to close the application before the next iteration. Alternatively, you might just keep it active the whole time. You might use one of the timer classes to fire events periodically, or even a Thread.Sleep in a very simplified scenario....
Related
I'm making a simple game on console for practice that requires a time limit each round and I've encountered a problem with trying to make it so I can use timer more than once. I have this:
class Program
{
static Timer timer = new Timer(1000);
static int t = 10;
static void Main(string[] args)
{
timer.Elapsed += Timer_Elapsed1;
timer.Start();
Console.ReadLine();
t = 10;
timer.Start();
Console.ReadLine();
}
My thoughts were that the 2nd timer.Start() would get the same result as the first, but nothing happens.
private static void Timer_Elapsed1(object sender, ElapsedEventArgs e)
{
t--;
Console.WriteLine("Hello!");
if (t == 0)
{
Console.WriteLine("Goodbye!");
timer.Stop();
}
}
Why is the second timer.Start() not doing anything? How do I make it so I can use timer.Start() again and it will do the same thing as the first time? I'm using System.Timers
NVM IT DOES WORK, IM JUST DUMB LOL
Try stopping or disabling the first timer before trying to start a second time.
C# - how do you stop a timer?
I fell compelled to give you some disclaimers:
First, console is not the right Environment for Game Development. Neither is any of the GUI techs. For games you got XNA (pretty dated) and with .NET Core a bunch of new Options. The important thing is that you have a Game Loop of some form. Or at least imitate one.
Secondly, I am unsure how well most Timers work in console apps. Most of them use callbacks wich usually require a MessageQueue - wich is a GUI feature. I guess you could try a Multithreading time, but then you have to relearn everything if you leave Console applications.
As for your code: I am unsure when the Timer tick happens since you specified no interval. But I guess either:
never
after the 2nd timer start
I have a console app that does not terminate using a code
new System.Threading.AutoResetEvent(false).WaitOne();
What I want to achieve: I would want to run a StopWatch and if it meets a condition it will run certain file manipulating codes. And then finally after the block of code, resets the timer and wait for it to be true again to rerun.
Problem: However, upon debugging I cant get my code to go through my conditions even it has already passed the required condition.
My Code:
static void Main(string[] args)
{
string mutex_id = "41585f436f766572743243494d";
using (System.Threading.Mutex mtx = new System.Threading.Mutex(false, mutex_id))
{
if(!mtx.WaitOne(0,false))
{
return;
}
processTimer = new Stopwatch();
processTimer.Start();
if (processTimer.Elapsed.Seconds > 10)
{
processTimer.Stop();
fileQueue = Directory.GetFiles(ConfigurationManager.AppSettings["WatchPath"], ConfigurationManager.AppSettings["Format"]).ToList();
}
//process the fileQueue
//..
//..
//processTimer.Reset(); -> Reset Timer to wait for another 10 sec and process again
new System.Threading.AutoResetEvent(false).WaitOne();
}
}
I have used a FileSystemWatcher before but I failed to get the process correctly(Like Consecutive/Concurrent file creations and such). Tried Threading and Timers as my question.
Now I'm trying to approach this issue from a new perspective. Hope some can enlighten me with this.
There is no "try again" in your code.
The code you've written does the following:
Create a mutex and lock it
If it already exists, close application
Start a stopwatch
Check if 10 seconds elapsed (which they didn't)
Create a new AutoResetEvent and wait for ever for it
You will need some loop that periodically checks if 10 seconds have passed and otherwise Sleep
I want to create a windows service that performs some really long and heavy work. The code is inside OnStart method like this:
protected override void OnStart(string[] args)
{
System.IO.File.WriteAllText(
#"C:\MMS\Logs\WinServiceLogs.txt",
DateTime.Now + "\t MMS Service started."
);
this.RequestAdditionalTime(5*60*1000);
this.RunService();
}
this.RunService() sends a request to WCF service library hosted on IIS. It does some really long processes, ranging from 1-20 min, depending on the data it has to process. This service that I'm writing is supposed to be scheduled to run every day in the morning. So far, it runs and works fine, but when the time goes over a few seconds or min, it generates timeout exception. This causes the windows service to be in unstable state, and I can't stop or uninstall it without restarting the computer. Since, I'm trying to create an automated system, this is an issue.
I did do this.RequestAdditionalTime(), but I'm not sure whether it's doing what it's supposed to or not. I don't get the timeout error message, but now I don't know how to schedule it so it runs every day. If the exception occurs, then it won't run the next time. There were several articles and SO's I found, but there's something I'm missing and I can't understand it.
Should I create a thread? Some articles say I shouldn't put heavy programs in OnStart, where should I put the heavy codes then? Right now, when the service starts, it does this huge data processing which makes the Windows Service status to "Starting", and it stays there for long time until either the program crashes due to timeout, or completes successfully. How can I start the service, then set the status to Running while the code is running to do some data processing?
Your situation might be better suited for a scheduled task as Lloyd said in the comments above. But if you really want to use a Windows service, this is what you would need to add/update in your service code. This will allow your service to list as started and not timeout on you. You can adjust the timer length to suit your needs.
private Timer processingTimer;
public YourService()
{
InitializeComponent();
//Initialize timer
processingTimer = new Timer(60000); //Set to run every 60 seconds
processingTimer.Elapsed += processingTimer_Elapsed;
processingTimer.AutoReset = true;
processingTimer.Enabled = true;
}
private void processingTimer_Elapsed(object sender, ElapsedEventArgs e)
{
//Check the time
if (timeCheck && haventRunToday)
//Run your code
//You should probably still run this as a separate thread
this.RunService();
}
protected override void OnStart(string[] args)
{
//Start the timer
processingTimer.Start();
}
protected override void OnStop()
{
//Check to make sure that your code isn't still running... (if separate thread)
//Stop the timer
processingTimer.Stop();
}
protected override void OnPause()
{
//Stop the timer
processingTimer.Stop();
}
protected override void OnContinue()
{
//Start the timer
processingTimer.Start();
}
I've tried to search for this on google and stackoverflow, but I'm not sure what to call it, so I can't find it.
How would I make a "loop" for the C# program, that runs every, say, 100 milliseconds? Similar to what Minecraft calls "ticks", or GameMaker calls "steps".
I can't figure out how to do this. I'm using visual studio, and I have a main window. There are things that I want to execute constantly, so I'm trying to figure out how to make a "step" or "update" function.
If you want it to run for 100 ms you would do this
System.Timers.Timer timer = new System.Timers.Timer(100);
public void Initialize(object sender, EventArgs e)
{
timer.Elapsed+=Elapsed;
}
public void Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//do stuff
}
Something else you can do, however I don't think this one is as efficient
using System.Threading;
Thread th = new Thread(new ThreadStart(delegate
{
while (true)
{
Thread.Sleep(100);
//do stuff
}
}));
Or, you can download monogame to make more elaborate games in c#
http://www.monogame.net/
It has its own gameTime control.
You could use the Timer control which can be set to tick at a given interval. The interval property is in Milliseconds so you would need Timer1.Interval = 100;
Are you thinking of a Timer?
http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx
Generates recurring events in an application.
How can I use a timer in my console application? I want my console application to work in the background and to do something every 10 minutes, for example.
How can I do this?
Thanks
Console applications aren't necessarily meant to be long-running. That being said, you can do it. To ensure that the console doesn't just exit, you have to have the console loop on Console.ReadLine to wait for some exit string like "quit."
To execute your code every 10 minutes, call System.Threading.Timer and point it to your execution method with a 10 minute interval.
public static void Main(string[] args)
{
using (new Timer(methodThatExecutesEveryTenMinutes, null, TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10)))
{
while (true)
{
if (Console.ReadLine() == "quit")
{
break;
}
}
}
}
private static void methodThatExecutesEveryTenMinutes(object state)
{
// some code that runs every ten minutes
}
EDIT
I like Boj's comment to your question, though. If you really need a long-running application, consider the overhead of making it a Windows Service. There's some development overhead, but you get a much more stable platform on which to run your code.
You can just use the Windows Task Scheduler to run your console application every 10 minutes.