使用Java(Spring)从数据库安排任务的最佳方法

时间:2015-11-02 20:03:01

标签: java spring scheduled-tasks polling

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

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
}
应该在" interval"中定义的每个间隔执行

任务。领域, 结果应该写入TaskResult表

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

我使用弹簧靴。

这里的最佳做法是什么?

1 个答案:

答案 0 :(得分:4)

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

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

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

@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封电子邮件,因为它每分钟运行一次:)