我想创建一个每天凌晨4点自动运行的服务,该方法会在调用时自动删除一些文件,我已经编写了代码,但我在服务中调用的方法没有被执行。下面我附上了我的代码,请有人建议我解决。
public partial class Scheduler : ServiceBase
{
System.Timers.Timer _timer;
public Scheduler()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try
{
_timer = new System.Timers.Timer();
_timer.Interval = 1 * 60 * 1000;//Every one minute
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start();
}
catch (Exception ex)
{
Library.WriteErrorLog(ex);
}
}
public void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Library.WriteErrorLog("Timer elapsed");
this.ExtractDataFromSharePoint();
}
public void ExtractDataFromSharePoint()
{
Library.WriteErrorLog("inside task");
ArchiveAdministration admin = new ArchiveAdministration();
admin.ArchiveAuto();
Library.WriteErrorLog("job completed");
_timer.Stop();
}
}
我的日志文件只有以下输出语句:
计时器已用完了 内部任务
我没有得到"工作完成"我已经包含的声明..
答案 0 :(得分:1)
由于您未完成作业已完成,因此在ExtractDataFromSharePoint方法中添加try catch子句会很有帮助:
public void ExtractDataFromSharePoint()
{
try
{
Library.WriteErrorLog("inside task");
ArchiveAdministration admin = new ArchiveAdministration();
admin.ArchiveAuto();
Library.WriteErrorLog("job completed");
_timer.Stop();
}
catch(Exception ex)
{
Library.WriteErrorLog(ex.Message); //or try to log the stacktrace also
}
}
抓住异常,如果你无法解决,请将其粘贴到此处以便能够帮助您