Abhay Singhania

Abhay Singhania

  • NA
  • 32
  • 14.6k

Service not running from a method

Mar 23 2017 7:36 AM
public partial class Service1 : ServiceBase
{
private Timer timer1 = null;

public Service1()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
timer1 = new Timer();
this.timer1.Interval = 21600000; //6 hrs
this.timer1.Elapsed +=new System.Timers.ElapsedEventHandler(this.timer1_Tick);
timer1.Enabled=true;
timer1.AutoReset = true;
Library.WriteErrorLog("test windows service started");



/* var result = RunProcess(@"C:\Webdata", "cmd.exe", "C:\\Webdata\\Copy_All.bat", false);// server path \\192.168.12.3\IT Dept\Common\webdata
// my path C:\Abhay\batfile
if (result == 0)
{
// success
Console.WriteLine("Sucess");
}
else
{
// failed ErrorLevel / app ExitCode
Console.WriteLine("failed try again");

}
*/

}

protected override void OnStop()
{
timer1.Enabled = false;
Library.WriteErrorLog("Test Service ended");
}

public void timer1_Tick(object sender, ElapsedEventArgs e)
{
//job

var result = RunProcess(@"C:\Webdata", "cmd.exe", "C:\\Webdata\\Copy_All.bat", false);
// my path C:\Abhay\batfile
if (result == 0)
{
// success
Console.WriteLine("Sucess");
}
else
{
// failed ErrorLevel / app ExitCode
Console.WriteLine("failed try again");
}


}

public int RunProcess(string workDir, string appName, string args, bool hide = false)
{

Process proc = new Process();
proc.StartInfo.UseShellExecute = false; //addition
args = "/c";
appName = "C:\\Webdata\\Copy_All.bat";
workDir = @"C:\Webdata";
proc.StartInfo.WorkingDirectory = workDir;//batrun
proc.StartInfo.FileName = appName;
proc.StartInfo.Arguments = args;
proc.StartInfo.CreateNoWindow = hide;

proc.Start();
proc.WaitForExit();

return proc.ExitCode;
}
}
}
This is the windows service, the problem is that the service is not getting into the timer tick event. i have to write the code on OnStart event to run it. 

Answers (3)