namespace Client
{
class Program
{
static TcpClient client = new TcpClient();
static bool isServerOn = false;
static void Main(string[] args)
{
Timer timer = new Timer(1000);
timer.Elapsed += Update;
timer.Enabled = true;
}
private static void Update(Object source, ElapsedEventArgs e)
{
try
{
client.Connect("127.0.0.1", 1233);
if (isServerOn) return;
isServerOn = true;
Console.WriteLine("Server is On");
} catch(Exception)
{
if (!isServerOn) return;
isServerOn = false;
Console.WriteLine("Server Is Off");
}
}
}
}
i got this code for my client and the timer dont run because the application close after i run it can someone tell me how to make the timer run and the application dont close at the same time
Well you can use a Console.ReadKey() or Console.ReadLine() method like below but you should actually make it a WindowsService application rather a normal console application
static void Main(string[] args)
{
Timer timer = new Timer(1000);
timer.Elapsed += Update;
timer.Enabled = true;
Console.ReadKey();
}
You can solve this using Tasks.
Try this or something like it:
static void Main(string[] args)
{
Task t = Task.Run(async () => {
do
{
Update();
await Task.Delay(1000);
} while (isServerOn);
});
t.Wait();
}
Related
How can I get a C# method to run on a timer? I found this example online but the DoStuffOnTimer() method below is not getting hit:
public void DoStuff()
{
var intervalMs = 5000;
var timer = new Timer(intervalMs);
timer.Elapsed += new ElapsedEventHandler(DoStuffOnTimer);
timer.Enabled = true;
}
private void DoStuffOnTimer(object source, ElapsedEventArgs e)
{
//do stuff
}
Or if you don't need very precise timer you always can create it yourself:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Temp
{
internal class Program
{
// this is the `Timer`
private static async Task CallWithInterval(Action action, TimeSpan interval, CancellationToken token)
{
while (true)
{
await Task.Delay(interval, token);
if (token.IsCancellationRequested)
{
return;
}
action();
}
}
// your method which is called with some interval
private static void DoSomething()
{
Console.WriteLine("ding!");
}
// usage sample
private static void Main()
{
// we need it to add the ability to stop timer on demand at any time
var cts = new CancellationTokenSource();
// start Timer
var task = CallWithInterval(DoSomething, TimeSpan.FromSeconds(1), cts.Token);
// continue doing another things - I stubbed it with Sleep
Thread.Sleep(5000);
// if you need to stop timer, let's try it!
cts.Cancel();
// check out, it really stopped!
Thread.Sleep(2000);
}
}
}
using System;
using System.Timers;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Program thisone = new Program();
thisone.DoStuff();
Console.Read();
}
public void DoStuff()
{
var intervalMs = 5000;
Timer timer = new Timer(intervalMs);
timer.Elapsed += new ElapsedEventHandler(DoStuffOnTimer);
timer.Enabled = true;
}
private void DoStuffOnTimer(object source, ElapsedEventArgs e)
{
//do stuff
Console.WriteLine("Tick!");
}
}
}
I've code which starts depending whether the underlying application runs in console services instead of threads for the tasks. Here is a small cut of the main method:
//ANSAR BANK THREAD
Thread AnsarBankThread = new Thread(Ansar);
Console.WriteLine("Start The AnsarBankThread");
AnsarBankThread.Start();
//MELLAT BANK THREAD
Thread MellatBankThread = new Thread(Mellat);
Console.WriteLine("Start The MellatBankThread");
MellatBankThread.Start();
This is the code which will be executed:
static void Ansar()
{
var AnsarBank1 = new AnsarBank();
if (Environment.UserInteractive)
{
AnsarBank1.Start();
}
else
{
var servicesToRun = new ServiceBase[]{ AnsarBank1 };
ServiceBase.Run(servicesToRun);
}
}
static void Mellat()
{
var MellatBank1 = new MellatBank();
if (Environment.UserInteractive)
{
MellatBank1.Start();
}
else
{
var servicesToRun = new ServiceBase[]{ MellatBank1 };
ServiceBase.Run(servicesToRun);
}
}
and this is my AnsarBank service code:
protected override void OnStart(string[] args)
{
var timer = new System.Timers.Timer(5000); // fire every 30 second
timer.Elapsed += OnElapsedTime;
timer.Enabled = true;
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
File.WriteAllText(#"d:\Temp\Ansar.txt", "Ansar Bank Writer\n");
}
public void Start()
{
OnStart(new string[0]);
}
And this is my MellatBank Service:
protected override void OnStart(string[] args)
{
var timer = new System.Timers.Timer(5000); // fire every 30 second
timer.Elapsed += OnElapsedTime;
timer.Enabled = true;
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
File.WriteAllText(#"d:\Temp\MellatBank.txt", "Mellat Bank writer\n");
}
public void Start()
{
OnStart(new string[0]);
}
However, if I run the code there will be only the file Ansar.txt created and the file MellatBank.txt is missing!
Can someone encounter the problem in my code please? I would appreciate any help!
Chnage code to this:
System.Timers.Timer personalTimer = null;
public AnsarBank()
{
personalTimer = new System.Timers.Timer(5000);
InitializeComponent();
}
protected override void OnStart(string[] args)
{
//var timer = new System.Timers.Timer(5000); // fire every 30 second
personalTimer.Elapsed += OnElapsedTimeAnsar;
personalTimer.Enabled = true;
}
but so not work.
What's the problem?
1. Variable goes out of scope:
Thanks to #MatthewWatson: I also suggest moving the timer variable outside of the method right into the class. The timer object can be garbage collected directly because the garbage collector doesn't see that it's used any further.
Why thinks the gc that the variable isn't used anymore?
Simply because you created it in the method. It's local and because the class itself hasn't any reference to it there isn't any hint for the gc that it's needed further!
This should be true after I looked to this question.
Solution to this in sample code:
class SomeClass {
System.Timers.Timer personalTimer = null; //Timer is now garbage collected after the object of SomeClass goes out of scope!
SomeClass() {
personalTimer = new Syste.Timers.Timer(30000) // Now every 30 seconds!
}
protected override void OnStart(string[] args)
{
personalTimer.Elapsed += OnElapsedTime;
personalTimer.AutoReset = true; //Add this line to keep continuos activation
personalTimer.Enabled = true;
}
....
}
2.File access problems
After I tried your code I encountered exceptions because the path may not exist. So I changed the code to create a path before the creation of a file. Also I added checks whether file exists and if so that text will be applied to the file. The old solution replaced the file everytime. This works for me fine. I don't know what you've done with InitializeComponents(...) this seems to be gui stuff, so I don't know.
Change your code in the service classes to following please:
namespace WebService
{
partial class MellatBank : ServiceBase
{
System.Timers.Timer personalTimer = null;
public MellatBank()
{
personalTimer = new System.Timers.Timer(1000);
this.ServiceName = "MellatBankService";
}
protected override void OnStart(string[] args)
{
personalTimer.Elapsed += OnElapsedTimeMellat;
personalTimer.AutoReset = true; //Add this line to keep continuos activation
personalTimer.Enabled = true;
//var timer = new System.Timers.Timer(5000); // fire every 30 second
//personalTimer.Elapsed += OnElapsedTimeMellat;
//personalTimer.Enabled = true;
}
private void OnElapsedTimeMellat(object source, ElapsedEventArgs e)
{
try
{
if (!Directory.Exists(#"D:\Temp"))
Directory.CreateDirectory(#"D:\Temp\");
if (!File.Exists(#"D:\Temp\MellatBank.txt"))
{
var f = File.CreateText(#"D:\Temp\MellatBank.txt");
f.Write(#"D:\Temp\MellatBank.txt", "Mellat Bank writer\n");
f.Close();
}
else
{
var f = File.AppendText(#"D:\Temp\MellatBank.txt");
f.Write("Mellat Bank writer\n");
f.Close();
}
}
catch (System.Exception ex)
{
Console.Error.WriteLine("IO EXCEPTION: {0}", ex.ToString());
}
}
public void Start()
{
OnStart(new string[0]);
}
protected override void OnStop()
{
Console.Out.WriteLine("ended!");
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}
}
namespace WebService
{
partial class AnsarBank : ServiceBase
{
System.Timers.Timer personalTimer = null;
public AnsarBank()
{
personalTimer = new System.Timers.Timer(1000);
this.ServiceName = "AnsarBankService";
}
protected override void OnStart(string[] args)
{
personalTimer.Elapsed += OnElapsedTimeAnsar;
personalTimer.AutoReset = true; //Add this line to keep continuos activation
personalTimer.Enabled = true;
//var timer = new System.Timers.Timer(5000); // fire every 30 second
//personalTimer.Elapsed += OnElapsedTimeAnsar;
//personalTimer.Enabled = true;
}
private void OnElapsedTimeAnsar(object source, ElapsedEventArgs e)
{
try
{
if (!Directory.Exists(#"D:\Temp"))
Directory.CreateDirectory(#"D:\Temp\");
if (!File.Exists(#"D:\Temp\Ansar.txt"))
{
var f = File.CreateText(#"D:\Temp\Ansar.txt");
f.Write(#"D:\Temp\Ansar.txt", "Ansar Bank writer\n");
f.Close();
}
else
{
var f = File.AppendText(#"D:\Temp\Ansar.txt");
f.Write("Ansar Bank Writer\n");
f.Close();
}
}
catch (System.Exception ex)
{
Console.Error.WriteLine("IO EXCEPTION: {0}", ex.ToString());
}
}
public void Start()
{
OnStart(new string[0]);
}
protected override void OnStop()
{
Console.Out.WriteLine("ended!");
}
}
}
Edit:
After viewing your code I saw that your services only run as long as your application runs. So your services may have been stopped before they could write anything which would explain your problem too.
PS:
Asker please practice the basics of Object Oriented Programming (OOP) again if you don't know what class fields are.
Is it possible to optimise my console application? It uses up to 60% of CPU because of while(true) loop.
The idea is to kill Microsoft managment console (services) process every time it starts up. And to start/stop services - use pswrd and console.
public static void Main(string[] args)
{
Thread consoleInput = new Thread(_consoleInput);
consoleInput.Start();
killProcess();
}
static void _consoleInput(){
getPassword();
sendServiceCommands();
}
static void killProcess(){
while(true){
try{
System.Diagnostics.Process[] myProcs = System.Diagnostics.Process.GetProcessesByName("mmc");
myProcs[0].Kill();
}
catch(Exception e){}
}
}
You need System.Threading.Timer. Something like this:
public class Killer
{
protected const int timerInterval = 1000; // define here interval between ticks
protected Timer timer = new Timer(timerInterval); // creating timer
public Killer()
{
timer.Elapsed += Timer_Elapsed;
}
public void Start()
{
timer.Start();
}
public void Stop()
{
timer.Stop();
}
public void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
try
{
System.Diagnostics.Process[] myProcs = System.Diagnostics.Process.GetProcessesByName("mmc");
myProcs[0].Kill();
}
catch {}
}
}
...
public static void Main(string[] args)
{
Killer killer = new Killer();
Thread consoleInput = new Thread(_consoleInput);
_consoleInput.Start();
killer.Start();
...
// whenever you want you may stop your killer
killer.Stop();
}
My timer elapsed event does not fire in my windows service, why? I search in the forum but nothing of the solutions work for me.
In the main of program.cs:
static class program
{
static void Main()
{
#if DEBUG
servicioCR cr = new servicioCR();
cr.beginProcess();
#else
#endif
//ServiceBase[] ServicesToRun;
//ServicesToRun = new ServiceBase[]
//{
// new servicioCR()
//};
//ServiceBase.Run(ServicesToRun);
}
}
In my service class
public static System.Timers.Timer timer;
public servicioCR()
{
timer = new System.Timers.Timer(5000);
timer.AutoReset = false;
timer.Elapsed += timer_Elapsed;
InitializeComponent();
}
The elapsed event
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
timer.Stop();
//Do stuff
}
catch (System.Exception ex)
{
EventLog.WriteEntry(ex.Message);
}
finally
{
timer.Start();
}
}
And the beginProcess()
internal void beginProcess()
{
timer.Start();
}
I am using .NET Framework 4.5 and VS 2013... I don't understand why it doesn't work, I copied this from another solution that works fine.
If I put a breakpoint in one line of the Do stuff on the elapsed event, it never breaks.
Why? Thanks
Your timer is running, but the program closes itself before the timer ever fires. You need to put a pause of some kind in so your program does not close itself.
static void Main()
{
#if DEBUG
servicioCR cr = new servicioCR();
cr.beginProcess();
Console.WriteLine("Program Running");
Console.ReadLine();
#else
#endif
//ServiceBase[] ServicesToRun;
//ServicesToRun = new ServiceBase[]
//{
// new servicioCR()
//};
//ServiceBase.Run(ServicesToRun);
}
Here is a snippit of code from one of my older projects, this lets you run your program as both a service and a console app. In Visual studio just set the debugger to pass in the arguments --console in the setup project screen.
class Program
{
public static void Main(string[] args)
{
var example = new MyExampleApp();
if (args.Contains("--console"))
{
example.ConsoleRun(args);
}
else
{
ServiceBase.Run(example);
}
}
}
class MyExampleApp : ServiceBase
{
public void ConsoleRun(string[] args)
{
Console.WriteLine(string.Format("{0}::starting...", GetType().FullName));
OnStart(args);
Console.WriteLine(string.Format("{0}::ready (ENTER to exit)", GetType().FullName));
Console.ReadLine();
OnStop();
Console.WriteLine(string.Format("{0}::stopped", GetType().FullName));
}
//... the rest of the code from your service class.
}
I am new to C# but java has method to execute specified task at the specified time so using c# how it doing
Timer t=new Timer();
TimerTask task1 =new TimerTask()
t.schedule(task1, 3000);
You can get a complete tutorial of how timer works in C# here : http://www.dotnetperls.com/timer
In Short:
using System;
using System.Collections.Generic;
using System.Timers;
public static class TimerExample // In App_Code folder
{
static Timer _timer; // From System.Timers
static List<DateTime> _l; // Stores timer results
public static List<DateTime> DateList // Gets the results
{
get
{
if (_l == null) // Lazily initialize the timer
{
Start(); // Start the timer
}
return _l; // Return the list of dates
}
}
static void Start()
{
_l = new List<DateTime>(); // Allocate the list
_timer = new Timer(3000); // Set up the timer for 3 seconds
//
// Type "_timer.Elapsed += " and press tab twice.
//
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
_timer.Enabled = true; // Enable it
}
static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
_l.Add(DateTime.Now); // Add date on each timer event
}
}
Using Anonymous Methods and Object Initializer:
var timer = new Timer { Interval = 5000 };
timer.Tick += (sender, e) =>
{
MessageBox.Show(#"Hello world!");
};
Here is a sample:
public class Timer1
{
public static void Main()
{
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 5 seconds.
aTimer.Interval=5000;
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!");
}
}
using System;
using System.Threading;
namespace ConsoleApplication6
{
class Program
{
public void TimerTask(object state)
{
//Do your task
Console.WriteLine("oops");
}
static void Main(string[] args)
{
var program = new Program();
var timer = new Timer(program.TimerTask,
null,
3000,
Timeout.Infinite);
Thread.Sleep(10000);
}
}
}