I'm try to use Quartz.net send email at time on everyday in asp.net MVC project. But it's work only once, it's not repeat everyday. Here my code
public class EmailJob: IJob
{
private static Logger _logger = LogManager.GetCurrentClassLogger();
public void Execute(IJobExecutionContext context)
{
_logger.Info(DateTime.Now.ToString);
}
}
public static void Start()
{
IScheduler _scheduler = StdSchedulerFactory.GetDefaultScheduler();
_scheduler = StdSchedulerFactory.GetDefaultScheduler();
IJobDetail job = JobBuilder.Create<EmailJob>().WithIdentity("theJob_").StoreDurably(true)
.UsingJobData("para", 1).Build();
_scheduler.AddJob(job, true);
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger3")
.ForJob(job)
.WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(8, 0))
.Build();
_scheduler.ScheduleJob(trigger);
_scheduler.Start();
_logger.Info(DateTime.Now.ToString() + "_scheduler start");
}
I call "JobScheduler.Start()" at global. Can anybody tell me where my code wrong? thank advance!
I think you are missing .RepeatForever()
. Your schedule will only run once.
But if it is very important that the mails are send at 8 sharp, then you should be using a server side solution like a service or scheduled task because there is no guarantee that the website is available.
You can use a job that runs every x minutes while the site is online. And should the apppool recycle, websites crashes or whatever, when it's online again it will immediately send the mails and again do so every 10 minutes.
IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
scheduler.Start();
IJobDetail job1 = JobBuilder.Create<Job_SendMail>().Build();
ITrigger trigger1 = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInMinutes(10)
.RepeatForever())
.Build();
scheduler.ScheduleJob(job1, trigger1);
public class Job_SendMail: IJob
{
void IJob.Execute(IJobExecutionContext context)
{
//do stuff
}
}
Avoid .RepeatForever()
, instead use .WithDailyTimeIntervalSchedule
with .StartingDailyAt
Example:
IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
scheduler.Start();
var hour = 12 //Start Time
var minute=15 //Start minute
IJobDetail job = JobBuilder.Create<Job_SendMail>().Build();
var time = DateTime.Now.AddSeconds(10);
ITrigger trigger = TriggerBuilder.Create()
.WithDailyTimeIntervalSchedule
(s =>
s.WithIntervalInHours(24)
.OnEveryDay()
.StartingDailyAt(TimeOfDay.HourMinuteAndSecondOfDay(hour, minute, time.Second))
)
.Build();
scheduler.ScheduleJob(job, trigger);