我有一个 Windows 服务,该服务应该以一定的时间间隔运行(目前出于测试目的设置为 1 分钟),并从我们的数据库获取数据,然后将信息上传到我们的 Google 日历。在 Debug模式下,一切运行良好,但是当 Windows 服务在我的 PC 上自行运行时,它似乎在“Inside StartGoogleCalendar”EventLog 条目处停滞。为什么它在 Debug模式下运行得很好,但在生产模式下却停滞不前?难道我做错了什么?下面是代码。
protected override void OnStart(string[] args)
{
EventLog.WriteEntry("Service Started: " + DateTime.Now.ToLongDateString());
_timer = new System.Timers.Timer(1 * 60 * 1000);
_timer.Elapsed += new System.Timers.ElapsedEventHandler(fireGoogle);
_timer.Start();
}
protected override void OnStop()
{
EventLog.WriteEntry("Service Stopped: " + DateTime.Now.ToLongDateString());
}
private void fireGoogle(object sender, System.Timers.ElapsedEventArgs e)
{
EventLog.WriteEntry("Firing Google: " + DateTime.Now.ToLongDateString());
StartGoogleCalendar();
}
public void StartGoogleCalendar()
{
try
{
EventLog.WriteEntry("Inside StartGoogleCalendar");
authorization Auth = new authorization();
EventLog.WriteEntry("Done with Auth");
calendar ipamCal = new calendar();
EventLog.WriteEntry(Auth.EventLogEvent());
EventLog.WriteEntry("GAPI Calendar Schedule complete");
}
catch (Exception ex)
{
EventLog.WriteEntry(ex.Data.ToString() + ": INNER EXCEPTION: " + ex.InnerException.ToString() + " - GENERAL MESSAGE: " + ex.Message.ToString() + " - SOURCE: " + ex.Source.ToString() );
}
}
这是“授权”代码(client_secrets.json 确实存在,因为它在 Debug模式下工作):
private static EventLog _el = new EventLog();
public authorization()
{
globals.scopes = new List<string>();
_authCredentials();
}
private void _authCredentials()
{
globals.scopes.Add("https://www.googleapis.com/auth/calendar");
try
{
_el.WriteEntry("Inside _authcredentials");
using (FileStream _stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
_el.WriteEntry("Attempting to get credentials");
globals.userCredentials = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(_stream).Secrets, globals.scopes, "Today-at-IPAM", CancellationToken.None, new FileDataStore("calendar_new.dat")).Result;
_el.WriteEntry(globals.userCredentials.Token.ToString());
}
_el.WriteEntry( "Google Authorization - SUCCESS");
}
catch (Exception ex)
{ _el.WriteEntry( "Google Authorization - FAILED\r\n\tReason: " + ex.InnerException.Message); }
}
public String EventLogEvent()
{ return globals.eventLogEvents; }
最佳答案
您必须测试几件事: 1/在windows系统中添加服务时是否指定了完整的执行路径 请引用命令行。 SC CREATE "ServiceName"DisplayName= "显示服务名称"binpath= "C:\User\Service.exe"start= auto obj= "NT AUTHORITY\LocalService"
2/您用来启动服务的帐户是什么,权限是否正确? 请引用上例中的参数obj。
3/“client_secrets.json”目录和文件的权限是什么
关于c# - Windows 服务停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25135457/