Datetime and offsets in .net
-
05-06-2021 - |
Question
How can I schedule a background job to start every day at 9pm in Colombian time? Im using quartz.net
public class Program
{
static void Main(string[] args)
{
// construct a scheduler
var schedulerFactory = new StdSchedulerFactory();
var scheduler = schedulerFactory.GetScheduler();
scheduler.Start();
TimeZoneInfo colombianTimezone = TimeZoneInfo.FindSystemTimeZoneById("SA Pacific Standard Time");
var colombianTimeNow = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local,
colombianTimezone);
var job = JobBuilder.Create<EmailsJob>().Build();
var now = DateTime.Now;
var trigger = TriggerBuilder.Create()
.StartAt(//INeedThisToStartEverydayat9pmColombianTime)
.WithSimpleSchedule(x => x.WithIntervalInHours(24).RepeatForever())
.Build();
scheduler.ScheduleJob(job, trigger);
}
}
The StartAt method takes a DateTimeOffset object.
Please help
Solution
Cron based scheduling might be better alternative for your needs.
TimeZoneInfo colombianTimezone = TimeZoneInfo.FindSystemTimeZoneById("SA Pacific Standard Time");
var job = JobBuilder.Create<EmailsJob>().Build();
var trigger = TriggerBuilder.Create()
.WithCronSchedule("0 0 21 * * ?", x => x.InTimeZone(colombianTimezone))
.Build();
scheduler.ScheduleJob(job, trigger);
OTHER TIPS
This should give you a DateTimeOffset for today at 9pm, converted to UniversalTime to pass to quartz.
TimeZoneInfo colombianTimezone = TimeZoneInfo.FindSystemTimeZoneById("SA Pacific Standard Time");
DateTime columbianTime9pm = TimeZoneInfo.ConvertTime(DateTime.Today.AddHours(21), TimeZoneInfo.Local,
colombianTimezone);
DateTimeOffset startAt = new DateTimeOffset(columbianTime9pm).ToUniversalTime();
I haven't tested it, but I think this will also define the trigger you want.
TimeZoneInfo colombianTimezone = TimeZoneInfo.FindSystemTimeZoneById("SA Pacific Standard Time");
DateTime startTime = TimeZoneInfo.ConvertTime(DateTime.Today.AddHours(21), TimeZoneInfo.Local,
colombianTimezone);
SimpleTrigger trigger = new SimpleTrigger("myTrigger",
null,
startTime,
null,
SimpleTrigger.RepeatIndefinitely,
TimeSpan.FromHours(24));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow