I am creating a windows service which has to run on specific days and time. I am passing these variables using an XML document. Here is my code for passing the values
static void Main()
{
ServiceBase[] ServicesToRun;
Service1= new Service1();
//Load setting from xml and assign to variables "daysToExec" and "timeToExec"
LoadSettings();
Service1.daysToExecute = daysToExec;
Service1.timeToExecute = timeToExec;
ServicesToRun = new ServiceBase[] { Service1 };
ServiceBase.Run(ServicesToRun);
}
The code for OnStart() in Service1.cs
protected override void OnStart(string[] args)
{
timer1.Enable = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
foreach (string DayToRun in daysToExecute)
{
if (DateTime.Now.DayOfWeek.ToString().ToUpper().Equals(DayToRun.ToUpper()) && DateTime.Now.ToShortTimeString().Equals(timeToExecute))
{
Process.Start("Path to executable");
}
}
}
But this is not starting the executable. Is there something wrong with this code.
Thanks.
I got the answer atlast. I was using System.Windows.Forms.Timer and for some reason it was not at all executing the timer_tick method. After using System.Timers.Timer it worked fine.
Thanks for your comments.
Related
I created a new Windows-Service project and added it to the services using sc.exe, but I am always getting the error when I try to execute the Service.
Code in Program:
static void Main() {
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
Code in ServiceBase:
public Service1() {
InitializeComponent();
}
protected override void OnStart(string[] args) {
while(true) {
Console.WriteLine("Message all 5 sec...");
Thread.Sleep(5000);
}
}
protected override void OnStop() {
Environment.Exit(0);
}
I tried extending the Timeout in Registry(ServicesPipeTimeout), Using Threads and owning the Service but i still get the error.
Any Help is appreciated.
Kind Regards
Your service will never get out of the onStart-callback because of the endless loop you have created there. So this is blocking and will never finish.
You need to use a timer for your use-case. Just start a timer in your OnStart method and it shall run as expected:
public Service1() {
InitializeComponent();
}
public OnStart(string[] args)
{
Timer timer = new Timer();
timer.Interval = 5000; // 5 seconds
timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
timer.Start();
}
public void OnTimer(object sender, ElapsedEventArgs args)
{
Console.WriteLine("Message all 5 sec...");
}
The timer will send an event every 5 seconds and the added ElapsedEventHandler will call your OnTimer-Method.
(As I'm new to WCF)
I want to add Quartz in Windows Communication Foundation (WCF) project.
And I also wants to know that which file or method execute first after run the application.
Instead of using Quartz, I used C# Timer.
The Timer class in C# represents a Timer control that executes a code block at a specified interval of time repeatedly.
//Timer Class
public class FileJob
{
private System.Timers.Timer ProcessTimer;
public void Start()
{
try
{
ProcessTimer = new System.Timers.Timer();
ProcessTimer.AutoReset = true;
ProcessTimer.Elapsed += new System.Timers.ElapsedEventHandler(ProcessTimer_Elapsed);
ProcessTimer.Interval = 300000; //5 minutes
ProcessTimer.Start();
}
catch (Exception ex)
{ }
}
private void ProcessTimer_Elapsed(object sender, EventArgs e)
{
UploadFile();
}
}
Global.asax.cs
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
FileJob obj = new FileJob();
obj.Start();
}
}
I created a Service in C#. I needed a GUI for configuration of the Service so I added a WinForms project to my solution. My plans was to create the Form in the Service and show it in the OnStart() Method of the Service. However, it won't show. The WriteEntry() Methods of the EventLog are all firing, so my code definitely is processed. Anybody know what I'm doing wrong here?
public partial class UrlWatcherService : ServiceBase
{
private UrlWatcherForm _urlwatcherform;
private EventLog _eventLog;
private string _eventLogName = "UrlWatcherEventLog";
private string _eventLogSource = "UrlWatcherSource";
public UrlWatcherService()
{
InitializeComponent();
LoadVariables();
}
public void OnDebug()
{
OnStart(null);
}
private void LoadVariables()
{
_urlwatcherform = new UrlWatcherForm();
_eventLog = new EventLog();
CanPauseAndContinue = true;
if (!EventLog.SourceExists(_eventLogSource))
EventLog.CreateEventSource(_eventLogSource, _eventLogName);
_eventLog.Source = _eventLogSource;
_eventLog.Log = _eventLogName;
_eventLog.WriteEntry("Url Watcher Log Created", EventLogEntryType.Information);
}
protected override void OnStart(string[] args)
{
_eventLog.WriteEntry("Url Watcher Service Started", EventLogEntryType.Information);
_urlwatcherform.Show();
_eventLog.WriteEntry("Url Watcher Form Created", EventLogEntryType.Information);
}
protected override void OnPause()
{
base.OnPause();
_eventLog.WriteEntry("Url Watcher Service Paused", EventLogEntryType.Information);
}
protected override void OnContinue()
{
base.OnContinue();
_eventLog.WriteEntry("Url Watcher Log Continued", EventLogEntryType.Information);
}
protected override void OnStop()
{
_eventLog.WriteEntry("Url Watcher Service Stopped", EventLogEntryType.Information);
}
}
public partial class UrlWatcherForm : Form
{
public UrlWatcherForm()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
}
private void UrlWatcherGui_Resize(object sender, EventArgs e)
{
if (FormWindowState.Minimized == WindowState)
Hide();
}
private void UrlWatcherGui_FormClosing(object sender, FormClosingEventArgs e)
{
Hide();
e.Cancel = true;
}
private void urlWatcherNofiyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
Show();
}
}
EDIT: To clarify, if I debug it like below, the Form shows. I can put the thread to sleep but that won't let me interact with the Form anymore. But the Form definitely shows, it's just in an unresponsive state.
static void Main()
{
#if DEBUG
UrlWatcherService service = new UrlWatcherService();
service.OnDebug();
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new UrlWatcherService()
};
ServiceBase.Run(ServicesToRun);
#endif
}
OK due to Steve's hint, I split the projects up. I use a merged module as per this MSDN article, and instead of referencing the GUI in the Service project, I separated them so I can put both their project outputs in the merged module. I then add the merged module to my installer and now I have the service running after install and the ability to call the form from my start menu. It's not what I originally wanted, but a very plausible alternative.
Thanks for Steve for the hint.
I have a service that I want to run every X min using (for example) a timer.
This is not working, why? Any better way I can do this? Tried searching and didn't found anything that worked for me...The breakpoint never hits OnStop method...
static void Main()
{
WriteLine("service has started");
timer = new Timer();
timer.Enabled = true;
timer.Interval = 1000;
timer.AutoReset = true;
timer.Start();
timer.Elapsed += scheduleTimer_Elapsed;
}
private static void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e)
{
WriteLine("service is runs again");
}
public static void WriteLine(string line)
{
Console.WriteLine(line);
}
I was in a bit same situation earlier. I used the following code, it worked for me.
// The main Program that invokes the service
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
//Now the actual service
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
///Some stuff
RunProgram();
///////////// Timer initialization
var scheduleTimer = new System.Timers.Timer();
scheduleTimer.Enabled = true;
scheduleTimer.Interval = 1000;
scheduleTimer.AutoReset = true;
scheduleTimer.Start();
scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed);
}
protected override void OnStop()
{
}
void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e)
{
RunProgram();
}
//This is where your actual code that has to be executed multiple times is placed
void RunProgram()
{
//Do some stuff
}
}
Hello
Lets say I have a console application, that looks like this
class Program
{
static void Main(string[] args)
{
}
public void DoSomething()
{
Console.WriteLine("Hello World");
}
}
}
I wan't to execute my DoSomething method every 10'th second by using System.Threading.timer. Can anyone give an example of how that is done?
Thanks in advance :)
Timer timer1 = new Timer(10000);
timer1.Enabled = true;
timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
timer1.Start();
static void timer1_Elapsed(object sender, ElapsedEventArgs e)
{
//Do Something
}
The documentation page for the System.Threading.Timer class has a lengthy, good example.