How to execute specified task at the specified time - c#

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);
}
}
}

Related

how to get a c# method to run on a timer?

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!");
}
}
}

How to stop the application from closing while timer is running

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();
}

C# -> Android (Xamarin) -> start task every 5 minutes in Background

i want to run a task every 5 minutes. i've tried to solve it with an IntentService and AlarmManager, my code:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
var tkrServiceIntent = new Intent(this, typeof(GpsDataHandler));
var tkrServicePendingIntent = PendingIntent.GetService(this, 0, tkrServiceIntent, 0);
long interval = 5000;
var firstStart = (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) + 1000;
var am = (AlarmManager)GetSystemService(Context.AlarmService);
am.SetInexactRepeating(AlarmType.RtcWakeup, firstStart, interval, tkrServicePendingIntent);
Toast.MakeText(this, "Service started", ToastLength.Long).Show();
}
i receive the toast, that the service is started, but if i look in running services, there is no service for my application. Can you tell me where the problem ist?
IntentService in an "activity" (if we can call it) runing in Background of the app, so finnally it will call the OnDestroy() ..
You can use the timer to fix your problem , like :
using System;
using System.Threading;
class TimerExampleState {
public int counter = 0;
public Timer tmr;
}
class App {
public static void Main() {
TimerExampleState s = new TimerExampleState();
// Create the delegate that invokes methods for the timer.
TimerCallback timerDelegate = new TimerCallback(CheckStatus);
// Create a timer that waits one second, then invokes every second.
Timer timer = new Timer(timerDelegate, s, 1000, 1000);
// Keep a handle to the timer, so it can be disposed.
s.tmr = timer;
// The main thread does nothing until the timer is disposed.
while (s.tmr != null)
Thread.Sleep(0);
Console.WriteLine("Timer example done.");
}
// The following method is called by the timer's delegate.
static void CheckStatus(Object state) {
TimerExampleState s = (TimerExampleState) state;
s.counter++;
Console.WriteLine("{0} Checking Status {1}.",DateTime.Now.TimeOfDay, s.counter);
if (s.counter == 5) {
// Shorten the period. Wait 10 seconds to restart the timer.
(s.tmr).Change(10000,100);
Console.WriteLine("changed...");
}
if (s.counter == 10) {
Console.WriteLine("disposing of timer...");
s.tmr.Dispose();
s.tmr = null;
}
}
}
Source : https://developer.xamarin.com/api/type/System.Threading.Timer/
Hope this code helps you:-
async void StartTimer()
{
await Task.Delay(60000); //60 seconds
// Do your code
StartTimer(); // Again Call
}
Call "StartTimer()" method where you want to. Call only once time then it calls automatically after 60 seconds.
Thanks !!!
you can create your own timer using xamarin forms device class
sample timer class:
public class Timer {
public Timer(int interval)
{
_interval = TimeSpan.FromMilliseconds(interval);
}
private bool _isRunning;
private readonly TimeSpan _interval;
private Action Tick;
public void Start(Action tick)
{
_isRunning = true;
Tick = tick;
Xamarin.Forms.Device.StartTimer(_interval,() =>
{
Tick?.Invoke();
return _isRunning;
});
}
public void Stop()
{
_isRunning = false;
Tick = null;
}
}
Create a service class. Call DoWork method in OnStartCommand method. Check whether the log is getting printed after every 5 seconds.
public void DoWork()
{
var t = new Thread(() =>
{
while (true)
{
Log.Debug("Service", "Service running");
Thread.Sleep(5000);
}
});
t.Start();
}

DispatcherTimer doesn't work in Console

I'm curious as to why dispatcher timer doesn't work in console mode. I created a simple alarm that does something when the timer reaches it's limit.
Can you use dispatcher timer with UnitTest or in Console mode?
DailyAlarm works when I run it in a form.
Here's my code to call the timer
[TestClass]
public class UnitTest1
{
bool runTest = true;
[TestMethod]
public void TestDailyAlarm()
{
DateTime alarmTime = new DateTime();
alarmTime= DateTime.Now;
alarmTime = alarmTime.AddSeconds(5);
// MessageBox.Show(alarmTime.ToString());
DailyAlarm alarm = new DailyAlarm(alarmTime);
alarm.DailyAlarmEvent += alarm_DailyAlarmEvent;
alarm.Start();
while (runTest)
{
System.Threading.Thread.Sleep(1000);
}
}
void alarm_DailyAlarmEvent(EventArgs e)
{
MessageBox.Show("Alarm On");
runTest = false;
}
}
Here's my timer code
public class DailyAlarm
{
#region Timer
DispatcherTimer timer;
#endregion
#region AlarmTime
DateTime _alarmTime;
#endregion
#region Event
public delegate void DailyAlarmHandler(EventArgs e);
public event DailyAlarmHandler DailyAlarmEvent;
#endregion
public DailyAlarm(System.DateTime alarmTime)
{
if (alarmTime < DateTime.Now)
{
alarmTime = alarmTime.AddDays(1);
}
_alarmTime = alarmTime;
TimeSpan timeRemaining = alarmTime.Subtract(DateTime.Now);
timer = new DispatcherTimer();
timer.Tick += AlarmEvent;
timer.Interval = timeRemaining;
}
public void Start()
{
timer.Start();
}
private void AlarmEvent(object sender, EventArgs e)
{
DailyAlarmEvent(null);
// Calculate next Alarm
_alarmTime = _alarmTime.AddDays(1);
TimeSpan timeRemaining = _alarmTime.Subtract(DateTime.Now);
Utilities.DispatcherTimer_ChangeInterval(ref timer, timeRemaining);
}
public void Stop()
{
if (timer != null)
timer.Stop();
}
}
The console and unit test environment by default don't have a dispatcher to run your dispatcher timer.
You can still use Dispatcher.CurrentDispatcher to create a Dispatcher to run your code.
There's an example of its usage at http://consultingblogs.emc.com/crispinparker/archive/2010/10/22/unit-testing-a-wpf-dispatchertimer-method.aspx
With this DispatcherHelper you can test your code with:
[TestMethod]
public void TestMethod1()
{
Action test = () =>
{
var dailyAlarm = new DailyAlarm(DateTime.Now.AddSeconds(5.0));
dailyAlarm.DailyAlarmEvent += dailyAlarm_DailyAlarmEvent;
dailyAlarm.Start();
};
DispatcherHelper.ExecuteOnDispatcherThread(test, 20);
}
void dailyAlarm_DailyAlarmEvent(EventArgs e)
{
// event invoked when DispatcherTimer expires
}
DispatcherTimer fires its Tick event on the UI thread. And you are running your code in a console mode. That's is the answer, I think!

Timer class and calling methods with passing parameter

I have a method that uses Timer class to call on a method and execute it on specific intervals.
private Timer tmr = new Timer();
public void WorkAtInterval(long interval, Action<object> work)
{
//heartbeat in miliseconds
tmr.Interval = interval;
tmr.Start();
tmr.Elapsed += new ElapsedEventHandler(work);
}
I have defined the function that has to be called like this:
private static void WorkSample (object interval)
{
Console.WriteLine("The interval is: {0}",interval);
}
and then eventually in my Main function:
static void Main(string[] args)
{
HeartBeat heart = new HeartBeat();
var interval = heart.HeartBeatInterval;
heart.WorkAtInterval(interval,sampleWork(interval));
Console.Read();
}
unfortunately, this even is not compiling. I am not that great with delegates.Any recommendation on how I can get this to work?
You can use a lambda expression:
heart.WorkAtInterval(interval, x => WorkSample(interval));
The solution is like this. The signature of the WorkAtInterval has to meet the signature ElapsedEventHandler. And then in the Main function the calling has to be done properly by anonymous function.
public void WorkAtInterval(long interval, Action<object,EventArgs> work)
{
//heartbeat in miliseconds
tmr.Interval = interval;
tmr.Start();
tmr.Elapsed += new ElapsedEventHandler(work);
}
private static void sampleWork(object interval)
{
Console.WriteLine("The interval is: {0}",interval);
}
static void Main(string[] args)
{
HeartBeat heart = new HeartBeat();
var interval = heart.HeartBeatInterval;
heart.WorkAtInterval(interval,(o,s) => sampleWork(interval));
Console.Read();
}

Categories