in this windows form app i use this Scheduler from Quartz.NET to trigger a job on certain time. Code works fine but i have an issue when executing the job and need to call something from the form outside the method created by the job. The (textBox1.Text) isnt inherited inside the method that is created on triggered job. (i think it has to do with the fact that Scheduler class is public async, any explanation is welcome)
namespace TaxControl
{
public partial class TaxControl : Form
{
.........................................
public class Scheduler
{
public async void Start()
{
ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
IScheduler scheduler = await schedulerFactory.GetScheduler();
await scheduler.Start();
IJobDetail job = JobBuilder.Create<Job>()
.WithIdentity("job", "group1")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("job", "group1")
.WithCronSchedule("0 36 18 * * ?")
.Build();
await scheduler.ScheduleJob(job, trigger);
}
}
public class Job : IJob
{
Task IJob.Execute(IJobExecutionContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
Task taskA = new Task(() => InfoControl());
taskA.Start();
return taskA;
}
public void InfoControl()
{
MessageBox.Show(textBox1.Text);
}
}
There are several problems with this code:
obviously, the
Job
class doesn't have the reference to thisTextBox
instance. This would normally be solved by writing aJob
constructor which accepts theTextBox
reference.However, to make Quartz.Net instantiate the job with parameterized constructor, you'll need to inject it using something like this, which is also often done using DI like this, or this.
Accessing
Control.Text
on a non-UI thread will throw an exception, so this means you will need to access the actual property by dispatching the call to the UI thread, or just simplify the whole thing by passing a simplestring
to yourJob
.You can also pass a
Func<string>
to the job's constructor, i.e. a function which returns astring
. This function also needs to do the UI access in a thread safe matter, but it will decouple the job logic from the actual UI.