我写了一个简单的任务bean,两个执行任务,时间是同一时刻,在数据库模式下只执行了一个任务。改为内存模式即可解决问题
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* 测试定时任务(演示Demo,可删除)
* <p>
* testTask为spring bean的名称
*
* @author crazySea
* @email 960236576@qq.com
*/
@Component("testTask")
public class TestTask implements ITask {
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void run(String params) {
logger.debug("TestTask定时任务正在执行,参数为:{}", params);
}
}
解决方案如下:
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import javax.sql.DataSource;
import java.util.Properties;
/**
* 定时任务配置
* 默认是单线程执行的,同一个时间触发的是串行执行的
* 使用内存模式就可以同一时刻执行多个任务
* @author KURO
*/
@Slf4j
@Configuration
public class ScheduleConfig{
@Bean
public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
// factory.setDataSource(dataSource);
//quartz参数
Properties prop = new Properties();
prop.put("org.quartz.scheduler.instanceName", "SlowcomScheduler");
prop.put("org.quartz.scheduler.instanceId", "AUTO");
//线程池配置
prop.put("org.quartz.threadPool.class", "org.quartz.simpl.SimpleThreadPool");
prop.put("org.quartz.threadPool.threadCount", "20");
prop.put("org.quartz.threadPool.threadPriority", "5");
//JobStore配置
//使用数据库定时任务
// prop.put("org.quartz.jobStore.class", "org.quartz.impl.jdbcjobstore.JobStoreTX");
//使用内存定时任务
prop.put("org.quartz.jobStore.class", "org.quartz.simpl.RAMJobStore");
// //集群配置
// prop.put("org.quartz.jobStore.isClustered", "true");
// prop.put("org.quartz.jobStore.clusterCheckinInterval", "15000");
// prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "1");
//
// prop.put("org.quartz.jobStore.misfireThreshold", "12000");
// prop.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
// prop.put("org.quartz.jobStore.selectWithLockSQL", "SELECT * FROM {0}LOCKS UPDLOCK WHERE LOCK_NAME = ?");
//PostgreSQL数据库,需要打开此注释
//prop.put("org.quartz.jobStore.driverDelegateClass", "org.quartz.impl.jdbcjobstore.PostgreSQLDelegate");
factory.setQuartzProperties(prop);
factory.setSchedulerName("SlowcomScheduler");
//延时启动
factory.setStartupDelay(0);
// factory.setApplicationContextSchedulerContextKey("applicationContextKey");
// //可选,QuartzScheduler 启动时更新己存在的Job,这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了
// factory.setOverwriteExistingJobs(true);
//设置自动启动,默认为true
factory.setAutoStartup(true);
return factory;
}
}