使用Java(Spring)从数据库调度任务的最佳方式



我正在寻找框架来调度数据库中填充的一组任务

JPA实体看起来像这个

@Entity
class Task extends Model {
    @NotNull
    @Min(1L)
    @Column(name = "interval_ms", nullable = false)
    Integer interval
    @NotNull
    String payload  
    @NotNull
    Boolean enabled
}
@Entity
class TaskResult extends Model {
    @ManyToOne(optional = false)
    Task task
    @Column(nullable = false)
    Boolean result
    @Column(nullable = false)
    String message
}

任务应该在"间隔"字段中定义的每个间隔执行,应将结果写入TaskResult表

任务的目的是发出GET或POST请求,因此必须对请求进行池化,以避免出现许多任务开始并行执行的情况。

我用的是弹簧靴。

这里的最佳实践是什么?

如果您使用的是Spring Boot,那么您可以使用TaskExecutor bean并配置池大小http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html#scheduling-任务执行器使用然后使用TaskScheduler来定义任务应该何时运行。此参数的事件值来自数据库(即Object)。

有一次我创建了调度器,但我使用了Quartz。我创建了newJob,它每1分钟触发一次(但你也可以使用毫秒),并在数据库中搜索EmailQueue,如果发现电子邮件,它会尝试发送,当发送出错时,他不会删除队列中的电子邮件,并在LOG表中写入有关错误的详细信息。调度程序(1分钟)是从数据库中设置的。在您的情况下,您应该使用:newJob(QuartzJob.class)。间隔为毫秒

http://quartz-scheduler.org/api/2.2.0/org/quartz/SimpleScheduleBuilder.html#withIntervalInMilliseconds(长)

@Service
public class MyQuartz implements InitializingBean, DisposableBean {
    @Autowired
    StdSchedulerFactory stdSchedulerFactory;
    @Autowired
    TableConfiguration tableConfiguration;
    Scheduler sched = null;
    JobDetail job, job2;
    JobDetail[] jobs = new JobDetail[2];
    public void initIt() throws Exception {
        try {
            System.out.println("Shedulling a job...");
            sched = stdSchedulerFactory.getScheduler();
        } catch (SchedulerException e) {
            System.err.println("Could not create scheduler.");
            e.printStackTrace();
        }
        try {
            System.out.println("Starting scheduler");
            sched.start();
        } catch (SchedulerException e) {
            System.err.println("Could not start scheduler.");
            e.printStackTrace();
        }
        // define the job and tie it to our QuartzJob class
        job = newJob(QuartzJob.class).withIdentity("myJob", "group1").build();
        job2 = newJob(QuartzCronJob.class).withIdentity("myCronJob", "group2")
                .build();
        jobs[0] = job;
        // .. here I have more jobs ...
        // Trigger the job to run now, and then every 5 minutes
        Trigger trigger = newTrigger()
                .withIdentity("myTrigger", "group1")
                .startNow()
                .withSchedule(
                        simpleSchedule().withIntervalInMinutes(
                                tableConfiguration.getTimeInterval())
                                .repeatForever()).build();
        // ... more triggers also here
        // Tell quartz to schedule the job using our trigger
        try {
            sched.scheduleJob(job, trigger);
            System.out.println("..job schedulled.");
        } catch (SchedulerException e) {
            System.err.println("Could not schedulle a job.");
            e.printStackTrace();
        }
    }
    @Override
    public void destroy() throws Exception {
        try {
            System.out.println("Stopping scheduler...");
            for (int i = 0; i < jobs.length; i++) { // Destroying all jobs
                sched.deleteJob(jobs[i].getKey());
            }
            sched.shutdown(true); // Waiting for jobs to complete.
            System.out.println("...scheduler Terminated. Good Bye.");
        } catch (SchedulerException e) {
            System.err.println("ERROR, scheduler cannot be stopped.");
            e.printStackTrace();
        }
    }
    @Override
    public void afterPropertiesSet() throws Exception {
    }
}

@Service
@Transactional
public class QuartzCronJob implements Job {
    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = new GregorianCalendar();
        String schedulled = sdf.format(calendar.getTime());
        System.out.println("LIST now " + schedulled);
        List<EmailQueue> emails = emailQueueDao.findAllForToday(schedulled);
        if (emails != null) {
            for (EmailQueue email : emails) {
                // Send email:
                try {
                    sendmail.sendNotification(email.getFrom(), email.getTo(),
                            email.getSubject(), email.getMessage(), "Sched.");
                    // Delete email from queue:
                    emailQueueDao.delete(email.getId());
                    System.out.println("Email sucessfully sent and deleted.");
                } catch (Exception e) {
                    sendmail.logEmail(LoggerSeverity.ERROR,
                            "Could not send schedulled email", "Sched.");
                    System.err.println("Could not send schedulled email");
                }
            }
        } 
        // ... more code here, this is just a working sample...
    }
}

我的代码没有使用池,但我没有从数据库中检索到超过3封电子邮件,因为它每分钟运行一次:)

相关内容

  • 没有找到相关文章

最新更新