Spring+Quartz----定时任务

任务有并行和串行之分,并行是指:一个定时任务,当执行时间到了的时候,立刻执行此任务,不管当前这个任务是否在执行中;串行是指:一个定时任务,当执行时间到了的时候,需要等待当前任务执行完毕,再去执行下一个任务。 

如果是通过MethodInvokingJobDetailFactoryBean在运行中动态生成的Job,配置的xml文件有个concurrent属性,这个属性的功能是配置此job是否可以并行运行,如果为false则表示不可以并行运行,否则可以并行。默认是true。


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--  Scheduler配置 -->
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="teachingProcessTrigger" />
            </list>
        </property>
        <property name="quartzProperties">
            <props>
                <prop key="org.quartz.threadPool.threadCount">3</prop>
            </props>
        </property>
    </bean>
<!--  Trigger配置 -->
    <bean id="teachingProcessTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail">
            <ref bean="teachingProcess" />
        </property>
        <property name="cronExpression">
            <!--  每天凌晨0点执行一次 -->
            <value>0 0 0 * * ?</value>
        </property>
    </bean>
<!--  JobDetail配置 -->
    <bean id="teachingProcess"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject">
    <!-- hrQuartzServiceImpl是一个业务类,在其他地方声明了bean,这里直接引用就可以 -->
            <ref bean="hrQuartzServiceImpl" />
        </property>
        <property name="targetMethod">
    <!-- hrQuartzServiceImpl类里作为执行入口的方法名 -->
            <value>doTeachingProcess</value>
        </property>
    </bean>
</beans>
<bean id="jobCompareB2cAndLocal" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    <property name="targetObject " ref="delegateJob " />
    <property name="targetMethod " value="方法名" />
    <property name="concurrent " value="false " />
</bean >

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这里是一个简单的 Spring-boot+Spring-batch+hibernate+Quartz 的批量读文件写数据的例子。 首先,需要在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-batch</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` 在 application.yml 文件中配置数据源和 Quartz: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true username: root password: root jpa: hibernate: ddl-auto: update show-sql: true quartz: job-store-type: jdbc jdbc: initialize-schema: always ``` 接下来,定义实体类 FileData: ```java @Entity @Table(name = "file_data") public class FileData { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "file_name") private String fileName; @Column(name = "line_number") private Integer lineNumber; @Column(name = "line_data") private String lineData; // getter and setter } ``` 定义读取文件的 ItemReader: ```java @Component @StepScope public class FileItemReader implements ItemReader<String> { private static final Logger LOGGER = LoggerFactory.getLogger(FileItemReader.class); private String file; private BufferedReader reader; @Value("#{jobParameters['file']}") public void setFile(String file) { this.file = file; } @BeforeStep public void beforeStep(StepExecution stepExecution) throws Exception { LOGGER.info("Starting to read file: {}", file); reader = new BufferedReader(new FileReader(file)); } @Override public String read() throws Exception { String line = reader.readLine(); if (line != null) { LOGGER.debug("Read line: {}", line); } else { LOGGER.info("Finished reading file: {}", file); reader.close(); } return line; } } ``` 定义处理数据的 ItemProcessor: ```java @Component public class FileItemProcessor implements ItemProcessor<String, FileData> { private static final Logger LOGGER = LoggerFactory.getLogger(FileItemProcessor.class); @Override public FileData process(String line) throws Exception { LOGGER.debug("Processing line: {}", line); String[] parts = line.split(","); FileData fileData = new FileData(); fileData.setFileName(parts[0]); fileData.setLineNumber(Integer.parseInt(parts[1])); fileData.setLineData(parts[2]); return fileData; } } ``` 定义写数据的 ItemWriter: ```java @Component public class FileItemWriter implements ItemWriter<FileData> { private static final Logger LOGGER = LoggerFactory.getLogger(FileItemWriter.class); @Autowired private EntityManager entityManager; @Override @Transactional public void write(List<? extends FileData> items) throws Exception { LOGGER.info("Writing {} items", items.size()); for (FileData item : items) { entityManager.persist(item); } entityManager.flush(); } } ``` 定义 Job: ```java @Configuration @EnableBatchProcessing public class BatchConfiguration { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Autowired private FileItemReader fileItemReader; @Autowired private FileItemProcessor fileItemProcessor; @Autowired private FileItemWriter fileItemWriter; @Bean public Job fileToDatabaseJob() { return jobBuilderFactory.get("fileToDatabaseJob") .incrementer(new RunIdIncrementer()) .start(step1()) .build(); } @Bean public Step step1() { return stepBuilderFactory.get("step1") .<String, FileData>chunk(10) .reader(fileItemReader) .processor(fileItemProcessor) .writer(fileItemWriter) .build(); } } ``` 定义 Quartz 定时任务: ```java @Component public class FileToDatabaseJobScheduler { @Autowired private SchedulerFactory schedulerFactory; @Autowired private JobDetail fileToDatabaseJobDetail; @Autowired private CronTriggerFactoryBean fileToDatabaseJobTrigger; @PostConstruct public void scheduleFileToDatabaseJob() throws SchedulerException { Scheduler scheduler = schedulerFactory.getScheduler(); scheduler.scheduleJob(fileToDatabaseJobDetail, fileToDatabaseJobTrigger.getObject()); scheduler.start(); } } ``` 最后,启动应用程序并将文件作为参数传递: ```java @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean @StepScope public FileItemReader fileItemReader(@Value("#{jobParameters['file']}") String file) { FileItemReader reader = new FileItemReader(); reader.setFile(file); return reader; } @Bean public JobDetail fileToDatabaseJobDetail() { return JobBuilder.newJob(BatchConfiguration.class) .withIdentity("fileToDatabaseJob") .storeDurably() .build(); } @Bean public CronTriggerFactoryBean fileToDatabaseJobTrigger(@Autowired JobDetail fileToDatabaseJobDetail) { CronTriggerFactoryBean trigger = new CronTriggerFactoryBean(); trigger.setJobDetail(fileToDatabaseJobDetail); trigger.setCronExpression("0 0/1 * 1/1 * ? *"); // 每分钟执行一次 return trigger; } } ``` 以上就是一个简单的 Spring-boot+Spring-batch+hibernate+Quartz 的批量读文件写数据的例子。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值