天天看點

spring的定時任務和異步方法

一、使用示例

1. 建立java工程,引入spring相關的jar包(略)

2. 在spring配置檔案中加入如下配置:

    <task:annotation-driven/>

    <context:component-scan base-package="com.tuozixuan.task"/>

 3. 編寫如下示例代碼并運作

package com.tuozixuan.task;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component("myTask")
public class MyTask
{
    @Scheduled(cron="0 0/5 10-12 * * ?")
    public void execute()
    {
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        System.out.println("[" + date + "]execute task...");
    }
    
    public static void main(String[] args)
    {
        ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring.xml"});
    }
}
           

二、spring定時任務詳解

1. @Scheduled配置

    @Scheduled(fixedRate=1000),fixedRate表明這個方法需要每隔指定的毫秒數進行周期性地調用。

    @Scheduled(fixedDelay=2000),fixedDelay用來指定方法調用之間的間隔(一次調用完成與下一次調用開始之間的間隔)。

    @Scheduled(cron="0 0/5 10-12 * * ?") cron用來指定這個方法在什麼時間調用。

    cron設定:

    1)秒(0-59)

    2)分鐘(0-59)

    3)小時(0-23)

    4)月份中的日期(0-31)

    5)月份(1-12或JAN-DEC)

    6)星期中的日期(1-7或SUN-SAT)

    7)年份(1970-2099)

    每個元素都可以顯式地指定值(如3)、範圍(如2-5)、清單(如2,4,7)或者通配符(如*)。

    月份彙總的日期和星期中的日期是互斥的,可以通過設定一個問号(?)來表明你不想設定的那個字段

三、異步方法

 1. 在Bean的方法上使用@Async進行注解,就可以使該方法成為一個異步執行的方法,代碼示例如下:

package com.tuozixuan.task;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component("myTask")
public class MyTask
{
    
    @Async
    public void executeAsync()
    {
        System.out.println("async execute task start...");
        try
        {
            Thread.sleep(5000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        System.out.println("async execute task end...");
    }
    
    public static void main(String[] args)
    {

        ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"spring.xml"});
        
        MyTask myTask =  context.getBean("myTask", MyTask.class);
        myTask.executeAsync();
        System.out.println("main...");
    }
}