我打算使用quartz.net来处理文件。如何在Quartz.net中使用多线程
- 我每小时会收到一个或多个文件,每个文件在不同国家会有1000行。
- 我想读取这些行,验证,处理并将其插入到多个表中。
- 我想选择1个文件,并为每个不同的国家在该文件中我喜欢创建一个线程。这样1个线程将处理1个国家的所有数据。
- 在给定的时间不应该有超过5个线程。
现在我该如何在quartz.net中定义这个?下面是我的代码中,我会通过文件中的每个文件,并通过行的每一行,我没有做任何多线程
调度作业
var properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "MyScheduler";
properties["quartz.threadPool.threadCount"] = "5";
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler s = sf.GetScheduler();
if (!s.IsStarted)
s.Start();
var jobKey = new JobKey("UniqueJobName", "BatchProcess");
if (s.GetJobDetail(jobKey) != null)
return "Error! Already running";
IJobDetail jobDetail = JobBuilder.Create<CountryProcessJob>()
.WithIdentity(jobKey)
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("UniqueTriggerName", "BatchProcess")
.StartAt(DateTime.Now.AddSeconds(1))
.Build();
s.ScheduleJob(jobDetail, trigger);
工作
public class CountryProcessJob : IJob
{
public void Execute(IJobExecutionContext context)
{
While() // TillAllFilesAreProcessed
{
// Read A File
While() //for each row in file
{
// validate
// Process
// Insert
}
}
}
}
我是否应该有一个主要的Job来循环遍历一个文件,然后在Job中定义多个Jobs来处理每个国家?这是如何实现石英多线程?
计划的主要工作
var properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "MyScheduler";
properties["quartz.threadPool.threadCount"] = "5";
ISchedulerFactory sf = new StdSchedulerFactory(properties);
IScheduler s = sf.GetScheduler();
if (!s.IsStarted)
s.Start();
var jobKey = new JobKey("UniqueJobName", "BatchProcess");
if (s.GetJobDetail(jobKey) != null)
return "Error! Already running";
IJobDetail jobDetail = JobBuilder.Create<FileProcessJob>()
.WithIdentity(jobKey)
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("UniqueTriggerName", "BatchProcess")
.StartAt(DateTime.Now.AddSeconds(1))
.Build();
s.ScheduleJob(jobDetail, trigger);
主要工作
public class FileProcessJob : IJob
{
public void Execute(IJobExecutionContext context)
{
while() // TillAllFilesAreProcessed
{
// Read A File
foreach(var eachCountry in file) //for each row in file
{
// Create a Job
var jobKey = new JobKey("UniqueCountryJobName", "BatchProcess");
if (s.GetJobDetail(jobKey) != null)
return "Error! Already running";
IJobDetail jobDetail = JobBuilder.Create<CountryProcessJob>()
.WithIdentity(jobKey)
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("UniqueCountryTriggerName", "BatchProcess")
.StartAt(DateTime.Now.AddSeconds(1))
.Build();
s.ScheduleJob(jobDetail, trigger);
}
}
}
}
每个国家
public class CountryProcessJob : IJob
{
public void Execute(IJobExecutionContext context)
{
// For each row for that country
// validate
// Process
// Insert
}
}
所以我应该创建多个职位,以实现多个线程在运行时创建多个作业同时?请帮助我在文件中运行5个并发线程处理每个不同的国家/地区。