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...");
    }
}

猜你喜欢

转载自tuozixuan.iteye.com/blog/2329685