Spring--简单使用quartz实现定时作业

定时批处理作业是J2EE企业应用里很重要的一环,用来在晚间进行财务挂账,数据转存,新闻联播等等操作。

    而在Spring里,已经很好的集成了Quartz,简单到像配cron一样,在xml文件里面配一下时间就可以自动执行,不需要写一行代码。Spring对Quartz大刀阔斧的简化堪称范例,Quartz项目组也许可以学习一下。

    <bean id="methodInvokingJobDetail"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject"><ref bean="financeDAO"/></property>
        <property name="targetMethod"><value>confirmOrder</value></property>
    </bean>

    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail">
            <ref bean="methodInvokingJobDetail"/>
        </property>
        <property name="cronExpression">
            <value>0 0 6,12,20 * * ?</value>
        </property>
    </bean>
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list><ref local="cronTrigger"/></list>
        </property>
    </bean>

上面这段配置文件规定了在早上6点和晚上8点执行financeDAO对象的confirmOrder()方法.


附:cronExpression配置说明

字段 允许值 允许的特殊字符
  0-59  , - * /
  0-59  , - * /
小时  0-23  , - * /
日期  1-31  , - * ? / L W C
月份  1-12 或者 JAN-DEC  , - * /
星期  1-7 或者 SUN-SAT  , - * ? / L C #
年(可选)  留空, 1970-2099  , - * /

The '*' character is used to specify all values. For example, "*" in the minute field means "every minute".
“*”字符被用来指定所有的值。如:”*“在分钟的字段域里表示“每分钟”。
The '?' character is allowed for the day-of-month and day-of-week fields. It is used to specify 'no specific value'. This is useful when you need to specify something in one of the two fileds, but not the other. See the examples below for clarification.
“?”字符只在日期域和星期域中使用。它被用来指定“非明确的值”。当你需要通过在这两个域中的一个来指定一些东西的时候,它是有用的。看下面的例子你就会明白。
The '-' character is used to specify ranges For example "10-12" in the hour field means "the hours 10, 11 and 12".
“-”字符被用来指定一个范围。如:“10-12”在小时域意味着“10点、11点、12点”。
The ',' character is used to specify additional values. For example "MON,WED,FRI" in the day-of-week field means "the days Monday, Wednesday, and Friday".
“,”字符被用来指定另外的值。如:“MON,WED,FRI”在星期域里表示”星期一、星期三、星期五”.
The '/' character is used to specify increments. For example "0/15" in the seconds field means "the seconds 0, 15, 30, and 45". And "5/15" in the seconds field means "the seconds 5, 20, 35, and 50". Specifying '*' before the '/' is equivalent to specifying 0 is the value to start with. Essentially, for each field in the expression, there is a set of numbers that can be turned on or off. For seconds and minutes, the numbers range from 0 to 59. For hours 0 to 23, for days of the month 0 to 31, and for months 1 to 12. The "/" character simply helps you turn on every "nth" value in the given set. Thus "7/6" in the month field only turns on month "7", it does NOT mean every 6th month, please note that subtlety.
The 'L' character is allowed for the day-of-month and day-of-week fields. This character is short-hand for "last", but it has different meaning in each of the two fields. For example, the value "L" in the day-of-month field means "the last day of the month" - day 31 for January, day 28 for February on non-leap years. If used in the day-of-week field by itself, it simply means "7" or "SAT". But if used in the day-of-week field after another value, it means "the last xxx day of the month" - for example "6L" means "the last friday of the month". When using the 'L' option, it is important not to specify lists, or ranges of values, as you'll get confusing results.
The 'W' character is allowed for the day-of-month field. This character is used to specify the weekday (Monday-Friday) nearest the given day. As an example, if you were to specify "15W" as the value for the day-of-month field, the meaning is: "the nearest weekday to the 15th of the month". So if the 15th is a Saturday, the trigger will fire on Friday the 14th. If the 15th is a Sunday, the trigger will fire on Monday the 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th. However if you specify "1W" as the value for day-of-month, and the 1st is a Saturday, the trigger will fire on Monday the 3rd, as it will not 'jump' over the boundary of a month's days. The 'W' character can only be specified when the day-of-month is a single day, not a range or list of days.
The 'L' and 'W' characters can also be combined for the day-of-month expression to yield 'LW', which translates to "last weekday of the month".
The '#' character is allowed for the day-of-week field. This character is used to specify "the nth" XXX day of the month. For example, the value of "6#3" in the day-of-week field means the third Friday of the month (day 6 = Friday and "#3" = the 3rd one in the month). Other examples: "2#1" = the first Monday of the month and "4#5" = the fifth Wednesday of the month. Note that if you specify "#5" and there is not 5 of the given day-of-week in the month, then no firing will occur that month.
The 'C' character is allowed for the day-of-month and day-of-week fields. This character is short-hand for "calendar". This means values are calculated against the associated calendar, if any. If no calendar is associated, then it is equivalent to having an all-inclusive calendar. A value of "5C" in the day-of-month field means "the first day included by the calendar on or after the 5th". A value of "1C" in the day-of-week field means "the first day included by the calendar on or after sunday".
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
城市应急指挥系统是智慧城市建设的重要组成部分,旨在提高城市对突发事件的预防和处置能力。系统背景源于自然灾害和事故灾难频发,如汶川地震和日本大地震等,这些事件造成了巨大的人员伤亡和财产损失。随着城市化进程的加快,应急信息化建设面临信息资源分散、管理标准不统一等问题,需要通过统筹管理和技术创新来解决。 系统的设计思路是通过先进的技术手段,如物联网、射频识别、卫星定位等,构建一个具有强大信息感知和通信能力的网络和平台。这将促进不同部门和层次之间的信息共享、交流和整合,提高城市资源的利用效率,满足城市对各种信息的获取和使用需求。在“十二五”期间,应急信息化工作将依托这些技术,实现动态监控、风险管理、预警以及统一指挥调度。 应急指挥系统的建设目标是实现快速有效的应对各种突发事件,保障人民生命财产安全,减少社会危害和经济损失。系统将包括预测预警、模拟演练、辅助决策、态势分析等功能,以及应急值守、预案管理、GIS应用等基本应用。此外,还包括支撑平台的建设,如接警中心、视频会议、统一通信等基础设施。 系统的实施将涉及到应急网络建设、应急指挥、视频监控、卫星通信等多个方面。通过高度集成的系统,建立统一的信息接收和处理平台,实现多渠道接入和融合指挥调度。此外,还包括应急指挥中心基础平台建设、固定和移动应急指挥通信系统建设,以及应急队伍建设,确保能够迅速响应并有效处置各类突发事件。 项目的意义在于,它不仅是提升灾害监测预报水平和预警能力的重要科技支撑,也是实现预防和减轻重大灾害和事故损失的关键。通过实施城市应急指挥系统,可以加强社会管理和公共服务,构建和谐社会,为打造平安城市提供坚实的基础。
### 回答1: 下面是一个简单Spring Boot + Spring Batch + Hibernate + Quartz的批量读文件写数据的例子: 1. 创建Spring Boot项目 首先,我们需要创建一个Spring Boot项目。可以使用Spring Initializr或者手动创建一个Maven项目。在pom.xml文件中添加相关依赖: ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-batch</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-quartz</artifactId> </dependency> </dependencies> ``` 2. 创建Job 接下来,我们要创建一个Job。Job是一个执行具体任务的实体,可以包含一个或多个Step。 ```java @Configuration public class JobConfiguration { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Autowired private DataSource dataSource; @Bean public FlatFileItemReader<Person> reader() { FlatFileItemReader<Person> reader = new FlatFileItemReader<>(); reader.setResource(new ClassPathResource("persons.csv")); reader.setLineMapper(new DefaultLineMapper<Person>() {{ setLineTokenizer(new DelimitedLineTokenizer() {{ setNames(new String[]{"firstName", "lastName", "email"}); }}); setFieldSetMapper(new BeanWrapperFieldSetMapper<Person>() {{ setTargetType(Person.class); }}); }}); return reader; } @Bean public PersonItemProcessor processor() { return new PersonItemProcessor(); } @Bean public JpaItemWriter<Person> writer() { JpaItemWriter<Person> writer = new JpaItemWriter<>(); writer.setEntityManagerFactory(entityManagerFactory().getObject()); return writer; } @Bean public Job importUserJob(JobCompletionNotificationListener listener) { return jobBuilderFactory.get("importUserJob") .incrementer(new RunIdIncrementer()) .listener(listener) .flow(step1()) .end() .build(); } @Bean public Step step1() { return stepBuilderFactory.get("step1") .<Person, Person>chunk(10) .reader(reader()) .processor(processor()) .writer(writer()) .build(); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource); em.setPackagesToScan("com.example.demo"); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; } private Properties additionalProperties() { Properties properties = new Properties(); properties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect"); return properties; } } ``` Job主要包含以下几个部分: - reader:读取文件中的数据 - processor:处理每一条数据 - writer:将数据写入数据库 - step:定义一个Step - job:定义一个Job,包含一个或多个Step 3. 创建任务调度 接下来,我们需要创建一个任务调度,使用Quartz实现。我们可以在应用启动时,自动启动任务调度。以下是一个简单的任务调度配置: ```java @Configuration public class SchedulerConfiguration { @Autowired private JobLauncher jobLauncher; @Autowired private Job importUserJob; @Bean public JobDetail jobDetail() { return JobBuilder.newJob().ofType(SpringJobAdapter.class) .storeDurably() .withIdentity("importUserJob") .withDescription("Invoke Spring batch from quartz") .build(); } @Bean public Trigger trigger(JobDetail job) { SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule() .withIntervalInSeconds(60) .repeatForever(); return TriggerBuilder.newTrigger().forJob(job) .withIdentity("importUserTrigger") .withDescription("Simple trigger") .withSchedule(scheduleBuilder) .build(); } @Bean public Scheduler scheduler(Trigger trigger, JobDetail job) throws SchedulerException { SchedulerFactory factory = new StdSchedulerFactory(); Scheduler scheduler = factory.getScheduler(); scheduler.scheduleJob(job, trigger); scheduler.setJobFactory(springBeanJobFactory()); scheduler.start(); return scheduler; } @Bean public SpringBeanJobFactory springBeanJobFactory() { return new AutowiringSpringBeanJobFactory(); } public class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements ApplicationContextAware { private transient AutowireCapableBeanFactory beanFactory; @Override public void setApplicationContext(ApplicationContext context) { beanFactory = context.getAutowireCapableBeanFactory(); } @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { final Object job = super.createJobInstance(bundle); beanFactory.autowireBean(job); return job; } } } ``` 这里我们使用Spring JobAdapter来将Spring Batch的Job包装成Quartz Job。同时,我们也定义了一个Simple Trigger,每隔60秒执行一次。 4. 编写数据处理逻辑 最后,我们需要编写具体的数据处理逻辑。这里我们简单的将读取到的Person数据插入到数据库中。以下是一个简单的数据处理类: ```java public class PersonItemProcessor implements ItemProcessor<Person, Person> { @Override public Person process(Person person) throws Exception { return person; } } ``` 5. 创建数据模型 在这个例子中,我们需要处理的数据是Person,我们需要创建一个Person类来描述数据模型: ```java @Entity public class Person { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String firstName; private String lastName; private String email; // getter and setter } ``` 6. 创建文件 最后,我们需要创建一个csv文件,用于存储测试数据。文件名为persons.csv,内容如下: ```csv firstName,lastName,email John,Doe,john.doe@example.com Jane,Doe,jane.doe@example.com Bob,Smith,bob.smith@example.com Alice,Smith,alice.smith@example.com ``` 7. 运行程序 完成以上步骤后,我们可以运行程序。当程序运行时,任务调度会定时执行任务,将csv文件中的数据插入到数据库中。 总的来说,这是一个简单Spring Boot + Spring Batch + Hibernate + Quartz的批量读文件写数据的例子。通过这个例子,可以熟悉Spring Batch的基本使用方法,并了解如何使用Quartz实现任务调度。 ### 回答2: Spring Boot是一种快速开发应用程序的框架,Spring Batch是Spring Boot的子项目,用于处理大量数据的批量处理任务。在这个用例中,我们可以使用Spring Boot、Spring Batch、Hibernate和Quartz实现简单的批量读取文件并写入数据。 首先,我们需要在Spring Boot项目中引入Spring Batch和Hibernate的依赖。然后,创建一个包含读取文件和写入数据的批处理任务。 使用Spring Batch的ItemReader接口从文件中逐行读取数据。你可以使用FlatFileItemReader类并配置文件路径、行解析器等属性来实现这一步骤。 接下来,使用Hibernate的Entity类和Repository来定义和操作数据表。根据业务需求,创建一个实体类并使用JPA注解配置。然后,创建一个Repository接口,用于查询和保存数据。 在批处理任务的写入步骤中,我们可以使用Hibernate的Session来保存数据。通过调用Repository的save方法,将读取到的数据写入数据库。 最后,使用Quartz来触发批处理任务。可以配置Quartz定时任务,按照一定的时间间隔或特定时间点触发批处理任务的执行。 在整个过程中,我们需要根据实际需求进行配置和开发,确保数据的正确读取和写入。可以使用Spring Boot自带的自动配置或者手动配置来实现以上功能。 综上所述,我们可以使用Spring Boot、Spring Batch、Hibernate和Quartz实现简单的批量读取文件并写入数据的用例。这个用例可以用来处理大量数据的批处理任务,实现数据的批量处理和定时执行。 ### 回答3: Spring Boot是一个用于创建独立的、基于Spring的生产级应用程序的框架。它简化了Spring应用程序的配置和部署过程,并提供了一套强大的开发工具和约定,使开发人员能够更快地构建应用程序。 Spring Batch是一个用于批量处理的框架。它提供了一种简单而强大的方式来处理大量的数据,并允许我们以可靠的方式处理失败和重试。它还提供了许多批处理作业开发和管理的功能,如读取数据源、处理数据并将结果写入目标数据源。 Hibernate是一个用于对象关系映射(ORM)的框架。它简化了Java应用程序与关系数据库之间的交互,并提供了一个对象导向的方式来操作数据。它提供了一种将对象持久化到数据库中的简单方式,并为开发人员提供了一套强大的查询语言(HQL)来执行复杂的数据库查询操作。 Quartz是一个用于任务调度的框架。它允许我们按照预定的时间间隔或时间短划进行任务调度。它还提供了一种强大的任务管理和监控机制,可以处理并发任务,并支持持久化任务调度信息。 下面是一个简单的批量读取文件并将数据写入数据库的示例: 1. 使用Spring Boot创建一个新的Web应用程序。 2. 导入Spring Batch、Hibernate和Quartz的依赖项。 3. 创建一个包含文件读取、数据处理和数据写入的Spring Batch作业。 4. 在作业使用Hibernate作为数据源读取文件的内容。 5. 配置Quartz来调度作业的执行。 6. 在作业实现一个写入数据库的处理器。 7. 配置Hibernate来将处理后的数据写入数据库。 8. 运行应用程序并观察任务按计划执行,并且文件中的数据被正确地写入数据库。 这个示例演示了如何使用Spring Boot、Spring Batch、Hibernate和Quartz来构建一个简单的批量处理应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值