Home Java javaTutorial Spring scheduled task implementation code in java

Spring scheduled task implementation code in java

Feb 07, 2017 pm 03:15 PM

import org.apache.log4j.*;
public class TaskJob {
       public static Logger log = Logger
                     .getLogger(TaskJob.class);
       public void SayHello() {
              // TODO Auto-generated method stub
              try {
                     log.info("处理任务开始>........");
                     // 业务逻辑代码调用
                     System.out.println("时间[" + new java.util.Date().toLocaleString()
                                   + "]----->大家好啊!");
                     log.info("处理任务结束!");
              } catch (Exception e) {
                     log.error("处理任务出现异常", e);
              }
       }
}
Copy after login

2. Next, configure it in spring:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean name="taskJob" class="util.TaskJob" />
    <bean id="methodInvokingJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
       <property name="targetObject">
           <ref bean="taskJob" />
       </property>
       <property name="targetMethod">
           <value>SayHello</value>
       </property>
    </bean>
    <!-- 配置触发器 -->
    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <!-- 这里不可以直接在属性jobDetail中引用taskJob,因为他要求的是一个jobDetail类型的对象,所以我们得通过MethodInvokingJobDetailFactoryBean来转一下 -->
       <property name="jobDetail">
           <ref bean="methodInvokingJobDetail" />
       </property>
       <!-- 每天的8点到21点每隔1分钟触发,具体说明见附录 -->
       <property name="cronExpression">
           <value>0 * 08-21 * * ?</value>
       </property>
    </bean>
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
       <!-- 添加触发器 -->
       <property name="triggers">
           <list>
              <ref local="cronTrigger" />
           </list>
       </property>
    </bean>
</beans>
Copy after login

3. To test the execution class, you can see the scheduled tasks running as long as you load the spring configuration file.

package util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestApp {

public static void main(String[] args) {
    // TODO Auto-generated method stub
        System.out.println("加载spring配置文件....");
      ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
      System.out.println("加载配置文件完毕!");
//   ApplicationContext context2 = new ClassPathXmlApplicationContext("test/timerTask/quartzTimer.xml");
}
}
Copy after login

If you want to run it in a web project, you also need to add the following code to web. Characters

seconds 0-59, - * /

minutes 0-59, - * /
hours 0-23, - * /
dates 1-31, - * ? / L W C
Month 1-12 or JAN-DEC, - * /
Week 1-7 or SUN-SAT, - * ? / L C
#Year (optional) Leave blank, 1970-2099, - * /
Expression meaning
"0 0 12 * * ?" Triggered every day at 12 noon
"0 15 10 ? * *" Triggered every day at 10:15 am
"0 15 10 * * ?" Every morning Triggered at 10:15
"0 15 10 * * ? *" Triggered every day at 10:15 AM
"0 15 10 * * ? 2005" Triggered every day at 10:15 AM in 2005
"0 * 14 * * ?" Triggers every 1 minute from 2 pm to 2:59 pm every day
"0 0/5 14 * * ?" Triggers every 5 minutes from 2 pm to 2:55 pm every day
"0 0/5 14,18 * * ?" Triggers every 5 minutes from 2pm to 2:55pm and every 5 minutes from 6pm to 6:55pm
"0 0-5 14 * * ?" " Triggers every 1 minute from 2pm to 2:05pm every day
"0 10,44 14 ? 3 WED" Triggers every Wednesday in March at 2:10pm and 2:44pm
"0 15 10 ? * MON-FRI" Triggered at 10:15 AM from Monday to Friday
"0 15 10 15 * ?" Triggered at 10:15 AM on the 15th of every month
"0 15 10 L * ?" Every Triggered at 10:15 am on the last day of the month
"0 15 10 ? * 6L" Triggered at 10:15 am on the last Friday of the month
"0 15 10 ? * 6L 2002-2005" 2002 to 2005 Triggered at 10:15 am on the last Friday of each month of the year
"0 15 10 ? * 6#3" Triggered at 10:15 am on the third Friday of each month

More spring timing in java For articles related to task implementation code, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte Mar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed Mar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

Node.js 20: Key Performance Boosts and New Features Node.js 20: Key Performance Boosts and New Features Mar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg: The Future of Data Lake Tables Iceberg: The Future of Data Lake Tables Mar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

How to Share Data Between Steps in Cucumber How to Share Data Between Steps in Cucumber Mar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

How can I implement functional programming techniques in Java? How can I implement functional programming techniques in Java? Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

See all articles