I have a windows service where in I want to create a file every 10 seconds.
I got many reviews that Timer in Windows service would be the best option.
How ca
This is how you do it simply
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.IO;
namespace MyService
{
public partial class Service1 : ServiceBase
{
Timer myTimer;
int x = 0;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
myTimer = new Timer(10000); // Sets a 10 second interval
myTimer.Elapsed +=new ElapsedEventHandler(myTimer_Elapsed);// Specifies The Event Handler
myTimer.Enabled = true; // Enables the control
myTimer.AutoReset = true; // makes it repeat
myTimer.Start(); // Starts the interval
}
protected void myTimer_Elapsed(object sender, ElapsedEventArgs e)
{
// All the Cool code that you need to run eg. Making a new file every 10 seconds
x++;
StreamWriter myFile = new StreamWriter("MyFile" + x.ToString() + ".txt");
myFile.Write("Something");
myFile.Close();
}
protected override void OnStop()
{
}
}
}
The Code above is the whole service with the timer. I realize this is an old post but it took me hours to figure this out. Hopefully it helps someone out there.