gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:21:36 26 4
gpt4 key购买 nike

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

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表

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

我正在使用 Spring Boot 。

此处的最佳做法是什么?

最佳答案

如果您使用的是 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,如果找到电子邮件,它会尝试发送它,当发送出错时,他不删除队列中的电子邮件并将有关错误的详细信息写入日志表。调度程序(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 封电子邮件,因为它每分钟运行一次 :)

关于java - 使用 Java (Spring) 从数据库安排任务的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33485882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com