Running a task in windows service - c#

I am making a windows service and one of its task is to ask for a free disk space every 1 hour, I know how to get the free space when the service starts but how to check for it every 1 hour?

Use a Timer like System.Timers.Timer:
var timer = new System.Timers.Timer();
timer.Elapsed += new ElapsedEventHandler(TimerElapsed);
timer.Interval = 60 * 60 * 1000; // 1 hour
timer.Enabled = true;
...
private static void TimerElapsed(object source, ElapsedEventArgs e)
{
// check disk space
}

Start thread:
while(true){
getFreeSpace();
Sleep(3600*1000);
};

Related

cycle in C#.NET win form

I have C#.NET program and I want to check something every 2 seconds until my form is closed. This cycle doesn't enable with user for other hand when user run my C#.NET form cycle is start until form closed.
For example I want to check internet connection when my form is used. I don't like checking the connection in form.load;. I want to check connection is every time.
this code is worked :
cycle Timer in winForm c#.NET
using Timer = System.Windows.Forms.Timer;
private void Form1_Load(object sender, EventArgs e)
{
Timer MyTimer = new Timer();
MyTimer.Interval = (45 * 60 * 1000); // 45 mins
MyTimer.Tick += new EventHandler(MyTimer_Tick);
MyTimer.Start();
}
private void MyTimer_Tick(object sender, EventArgs e)
{
//Check for internet connection or some other work here
Timer MyTimer = new Timer();
MyTimer.Interval = (45 * 60 * 1000); // 45 mins
MyTimer.Tick += new EventHandler(MyTimer_Tick);
MyTimer.Start();
}

Stop recording video after 15seconds

I am trying to stop video playback after 15 seconds but it's not working. Please suggest me how to achieve this?
CameraCaptureUI captureUI = new CameraCaptureUI();
captureUI.VideoSettings.Format = CameraCaptureUIVideoFormat.Mp4;
StorageFile videoFile = await captureUI.CaptureFileAsync(CameraCaptureUIMode.Video);
if (videoFile == null)
{
// User cancelled photo capture
return;
}
Using System.Timers you can achieve that. I don't know much about the library you are using, but using Timer i assume you can do it pretty easily.
using System.Timers;
static void Main(string[] args)
{
Timer tmr = new Timer();
int seconds = 15; // Not needed, only for demonstration purposes
tmr.Interval = 1000 * (seconds); // Interval - how long will it take for the timer to elapse. (In milliseconds)
tmr.Elapsed += Tmr_Elapsed; // Subscribe to the event
tmr.Start(); // Run the timer
}
private static void Tmr_Elapsed(object sender, ElapsedEventArgs e)
{
// Stop the video
}

C# How to run delayed method in between timer ticks

I am using a timer to run a method every 16 minutes. I also want to run a second method every minute for 15 minutes in-between.
Below is the code I am using:
int count = 0;
private void cmdGo_Click(object sender, EventArgs e)
{
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 960000; // specify interval time - 16 mins
t.Tick += new EventHandler(timer_Tick);
t.Start();
}
void timer_Tick(object sender, EventArgs e)
{
RunMethod1();
while(count < 15)
{
//waiting for 60 seconds
DateTime wait = DateTime.Now;
do
{
Application.DoEvents();
} while (wait.AddSeconds(60) > DateTime.Now);
RunMethod2();
}
}
The above code seems to work fine but the ‘do while’ loop to wait for 60 seconds is very CPU heavy.
I tried to use Thread.Sleep(60000) but this freezes up the Interface and also tried to add a second timer within timer_Tick but this doesn’t seem possible. Can a second timer be added within the EventHandler of the first?
Is there any other method to achieve this without being so CPU intensive?
Thanks!
Warren
NOTE: Sorry guys, there was a typo in my original post. The 60 second wait do, while loop should have been within the while < 15 loop. Just updated the code snippet.
So:
RunMethod1() should be executed every 16 mins
RunMethod2() should be executed every 1 min (15 times) in between the 16 min tick
It would make more sense to have a counter to store how many times the clock has gone off. Then set your timer interval to fire once a minute so not doing anything in between...
That way you could just do...
private int Counter;
private void cmdGo_Click(object sender, EventArgs e)
{
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 60000; // specify interval time - 1 minute
t.Tick += new EventHandler(timer_Tick);
t.Start();
}
// Every 1 min this timer fires...
void timer_Tick(object sender, EventArgs e)
{
// If it has been 16 minutes then run RunMethod1
if (++Counter >= 16)
{
Counter = 0;
RunMethod1();
return;
}
// Not yet been 16 minutes so just run RunMethod2
RunMethod2();
}
You could await a task Delay so the UI will keep responding
async void timer_Tick(object sender, EventArgs e)
{
RunMethod1();
while (count < 15)
{
//waiting for 60 seconds
await Task.Delay(60000);
RunMethod2();
}
}

C# Countdown Timer Then Do Something

Looked everywhere, but everywhere i look theres a different way to do a countdown timer. Finally found some simple code. How do I make it do something when the time is complete.
This part is next to InitializeComponent();
timerlabel1.Text = TimeSpan.FromMinutes(720).ToString();
private void countdownTimer()
{
var startTime = DateTime.Now;
var timer = new Timer() { Interval = 1000 };
timer.Tick += (obj, args) =>
timerlabel1.Text =
(TimeSpan.FromMinutes(720) - (DateTime.Now - startTime))
.ToString("hh\\:mm\\:ss");
timer.Enabled = true;
}
This is where i need help, how do i make it do something when the time is done. I tried if timer.Enabled =false; Do This. Cant figure it out.
Solution : you can assign the total seconds [TotalMinutes*60] into some variable and decrement each time the Timer Tick event raises.
if the totalseconds value becomes zero then stop the timer by calling timer.Stop() method.
Try This:
public int tootalsecs = 720 * 60;
private void countdownTimer()
{
var startTime = DateTime.Now;
var timer = new Timer() { Interval = 1000 };
timer.Tick += (obj, args) =>
{
if (tootalsecs==0)
{
timer.Stop();
}
else
{
timerlabel1.Text =
(TimeSpan.FromMinutes(720) - (DateTime.Now - startTime))
.ToString("hh\\:mm\\:ss");
tootalsecs--;
}
};
timer.Start();
}
try this may work for you
var timer=new Timer();
timer.Interval=1000;
timer.tick += timer_Tick;
timer.Start();
int i=0;
void timer_Tick(object sender, EventArgs e)
{
if(i<TimeSpan.FromMinutes(720))
{
timerlabel1.Text =
(TimeSpan.FromMinutes(720) - (DateTime.Now - startTime))
.ToString("hh\\:mm\\:ss");
}
else
{
timer.Stop();
/* do other work Here */
}
i++;
}
Try with this may work for you.
As there are couple Timer classes available (System.Windows.Forms.Timer, System.Threading.Timer and System.Timers.Timer) I will advice you to go with System.Timers.Timer.
It provides Elapsed event, instead of Tick event. That's what you're looking for.
// Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
You can try to do as below.
Initialize in global scope.
var target;
timerlabel1.Text =target= DateTime.Now.Add(TimeSpan.FromMinutes(720));
Add a Timer and in timer1_Tick write the below code
var span = targetTime - DateTime.Now;
if (span.TotalSeconds > 0)
{
//it will continue till the time ends.
var temp = span.ToString();
temp=temp.Substring(0, 8);
timerlabel1.Text = temp;
}
else
//do your work here
Don't forget to validate the answer or mark as answer if it close to your need

Windows service is not starting after first successfull run

I created a windows service, which will send mails to users based up on some conditions.
I had it installed on server in automatic mode. From the logs i can see that it ran successfully for first time and ended.
And i did not see it running again in the logs after that.
I checked the service in admin tools and it says it is started.
I also restarted service but no use, it did not start again.
Below is the code i used to start the service.
public partial class ScheduledService : ServiceBase
{
Timer timer;
private DateTime lastRun = DateTime.Now;
private DateTime DailyRunTime = Convert.ToDateTime(System.Configuration.ConfigurationManager.AppSettings["DailyRunTime"]);
public ScheduledService()
{
InitializeComponent();
//GetDocRetentionList DocList = new GetDocRetentionList();
//DocList.GetDataSet();
}
protected override void OnStart(string[] args)
{
//System.Diagnostics.Debugger.Launch();
TraceService("start service");
//timer = new Timer(24 * 60 * 60 * 1000);
timer = new Timer(10 * 60 * 1000);
timer.Start();
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
double TimerInterval = Convert.ToDouble(System.Configuration.ConfigurationManager.AppSettings["Timer"]);
timer.Interval = TimerInterval;
timer.Enabled = true;
}
protected override void OnStop()
{
timer.Enabled = false;
TraceService("stopping service");
}
private void OnElapsedTime(object source, ElapsedEventArgs e)
{
TraceService("Service started at " + DateTime.Now);
if (lastRun.Date < DateTime.Now.Date)
{
if (DateTime.Now > DailyRunTime)
{
GetDocRetentionList DocList = new GetDocRetentionList();
DocList.GetDataSet();
timer.Stop();
lastRun = DateTime.Now.Date;
//timer.Start();
}
}
}
Any help i can get in this regard will be really helpful. Plz let me know.
Well.. your service is set to execute once, then it shuts the timer off in the OnElapsedTime method but never turns itself back on.
The first thing OnElapsedTime should do is turn off the timer. The last thing it should do is turn it back on.

Categories