简而言之,我想在每5分钟调用一个方法,但仅限于工作时间。起初我试图使用Thread.Sleep()
,在每次调用时,我都试图计算睡眠时间。不知何故,它运作得不好。
以下是计算睡眠时间的代码。
void Main()
{
while(true)
{
Work()
Thread.Sleep(GetSleepTime());
}
}
int GetSleepTime()
{
int time = 0;
var now = DateTime.Now;
var isWorkingTime = false;
switch (now.DayOfWeek)
{
case DayOfWeek.Saturday:
case DayOfWeek.Sunday:
break;
default:
if (now.Hour >= 10 && now.Hour <= 19)
{
time = 5 * 60 * 1000;
isWorkingTime = true;
}
break;
}
if (!isWorkingTime)
{
int remainingDays = 1;
switch (now.DayOfWeek)
{
case DayOfWeek.Friday:
remainingDays = 3;
break;
case DayOfWeek.Saturday:
remainingDays = 2;
break;
}
DateTime nextWorkingday = now.AddDays(remainingDays).Date;
DateTime nextWorkingday10 = nextWorkingday.AddHours(10);
time = (int)(nextWorkingday10 - now).TotalMilliseconds;
}
return time;
}
使用Quartz.NET是否合适?如果是这样,我怎么能用它做同样的事情?
答案 0 :(得分:1)
你不需要睡觉。 Quartz.net旨在处理调度部分。 您需要创建一个作业及其触发器。
* 0/5 9,17 * * MON-FRI
以上触发器将从上午9点到下午5点每5分钟执行一次作业
以下是备选方案:
如果您使用的是v2 +,则可以在代码中使用以下触发器定义。
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.WithDailyTimeIntervalSchedule(
x => x.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(9, 0))
.EndingDailyAt(TimeOfDay.HourAndMinuteOfDay(17, 0))
.OnMondayThroughFriday()
.WithIntervalInMinutes(5))
.Build();