Spring-Task

1、这是网上的: 后面是我自己的配置

Spring3.0以后自主开发的定时任务工具,spring task,可以将它比作一个轻量级的Quartz,而且使用起来很简单,除spring相关的包外不需要额外的包,而且支持注解和配置文件两种形式,下面将分别介绍这两种方式。

第一种:配置文件方式

第一步:编写作业类

即普通的pojo,如下:

import org.springframework.stereotype.Service;
@Service
public class TaskJob { public void job1() {
System.out.println(“任务进行中。。。”);
}
}

 第二步:在spring配置文件头中添加命名空间及描述

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
。。。。。。
xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

 第三步:spring配置文件中设置具体的任务

说明:ref参数指定的即任务类,method指定的即需要运行的方法,cron及cronExpression表达式,具体写法这里不介绍了,详情见上篇文章附录。

<context:component-scan base-package="com.gy.mytask" />这个配置不消多说了,spring扫描注解用的。

到这里配置就完成了,是不是很简单。

第二种:使用注解形式

也许我们不想每写一个任务类还要在xml文件中配置下,我们可以使用注解@Scheduled,我们看看源文件中该注解的定义:

可以看出该注解有三个方法或者叫参数,分别表示的意思是:

cron:指定cron表达式

fixedDelay:官方文档解释:An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds.即表示从上一个任务完成开始到下一个任务开始的间隔,单位是毫秒。

fixedRate:官方文档解释:An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds.即从上一个任务开始到下一个任务开始的间隔,单位是毫秒。

下面我来配置一下。

第一步:编写pojo

 第二步:添加task相关的配置:

说明:理论上只需要加上<task:annotation-driven />这句配置就可以了,这些参数都不是必须的。

Ok配置完毕,当然spring task还有很多参数,我就不一一解释了,

具体参考xsd文档http://www.springframework.org/schema/task/spring-task-3.0.xsd。

2、这是我自己的配置,可以正常运行的

在springmvc-servlet.xml 中配置:

<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd" > <!-- Enables the Spring Task @Scheduled programming model -->
<task:executor id="executor" pool-size="5"/>
<task:scheduler id="scheduler" pool-size="10"/>
<task:annotation-driven executor="executor" scheduler="scheduler"/> <context:annotation-config /> </beans>

在java中的配置:

/**
* com.zywang.spring.task.SpringTaskDemo.java
* @author ZYWANG 2011-3-9
*/
package com.linemessage.application.module.messageschedule; import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; /**
* Spring3 @Scheduled 演示
* @author ZYWANG 2011-3-9
*/
@Component
public class StartSchedule { @Autowired
private TMessageScheduleDAO iMssageScheduleDao; @Autowired
private TMessageDAO iMssageDao;
@Autowired
private PrdCataDAO prdCataDAO; @Autowired
private TGroupDAO iGroupDAO;
@Autowired
private TGroupUserRelDAO iGroupUserRelDAO; @Autowired
private TProductDAO iProductDao; @Autowired
private UserSubDAO iUserSubDao; @Autowired
private TMessageStatusDAO iMssageStatusDao; @Autowired
private TMessageDurationDAO iMssageDurationDao; @Autowired
private TLocationDescDAO iTLocationDescDAO; @Autowired
private ClientUserDAO iClientUserDao;
@Autowired
private TPublisherDAO iTPublisherDAO; @Autowired
private TGroupUserRelDAO tGroupUserRelDAO; @Autowired
private PublisherProductRelDAO publisherProductRelDao; @Autowired
private TSubscribeDAO tSubScribeDAO; @Scheduled(cron = "0 0/15 * * * ?")//每15分钟运行一次
void messageSchdule() throws SQLException{
//System.out.println("I'm doing with cron now!"); Date end_time = new Date();
Date begin_time =new Date(end_time.getTime()-15*60*1000); //暂时设置为15分钟与cron对应
TMessageScheduleExample scheduleE = new TMessageScheduleExample();
scheduleE.createCriteria().andSendTimeBetween(begin_time,end_time).andIsvalidateEqualTo("1"); List<TMessageSchedule> schedules= iMssageScheduleDao.selectByExample(scheduleE); for(TMessageSchedule tms:schedules)
{
//从数据库取出消息
TMessageExample messageE = new TMessageExample();
messageE.createCriteria().andIdEqualTo(tms.getId()); List<TMessage> messages= iMssageDao.selectByExampleWithBLOBs(messageE);
TMessage message=messages.get(0); //取出接收人
TMessageStatusExample statusExample = new TMessageStatusExample();
statusExample.createCriteria().andMessageIdEqualTo(tms.getId());
List<TMessageStatus> statusList=iMssageStatusDao.selectByExample(statusExample);
//为所以接收人设置缓存 for(TMessageStatus status:statusList)
{
UserMessageCache.store(status.getDevicetoken(), "" + message.getId());
} //存储APPLE 手机的PUSHTOKEN
List<String> applehash= new ArrayList<String>(); List<TMessageStatus> appleList=iMssageStatusDao.selectByExample4Apple(statusExample); for (TMessageStatus status:appleList)
{ //如果是APPLE用户,则发送通知
applehash.add(status.getDevicetoken());
} // 创建缓存,给终端用户使用,缓存对像
SendMessage.store(message.getId() + "", message); //如果是苹果用户,发送通知
AppleSend sender= new AppleSendImpl(applehash,message.getTitle());
sender.send(); //做完之后,将t_mnessage_schedule的状态置为false // message
TMessageSchedule messageSchedule = iMssageScheduleDao
.selectByPrimaryKey(message.getId());
messageSchedule.setIsvalidate("0");
iMssageScheduleDao.updateByPrimaryKeySelective(messageSchedule); } //==以下为清除过期Message
TMessageDurationExample TMDExample = new TMessageDurationExample();
TMDExample.createCriteria().andIsvalidateEqualTo("1").andEndTimeLessThan(new Date());
List<TMessageDuration> messageDList=iMssageDurationDao.selectByExample(TMDExample);
for(TMessageDuration tms:messageDList)
{ tms.setIsvalidate("0");
iMssageDurationDao.updateByPrimaryKeySelective(tms); TMessageStatusExample statusExample = new TMessageStatusExample();
statusExample.createCriteria().andMessageIdEqualTo(tms.getMessageId()).andStatusNotEqualTo("0");
List<TMessageStatus> statusList=iMssageStatusDao.selectByExample(statusExample);
List<String>userIds=new ArrayList<String>();
for(TMessageStatus status:statusList)
{
userIds.add(status.getDevicetoken()); }
for (String deviceToken:userIds)
{
UserMessageCache.remove(deviceToken,String.valueOf(tms.getMessageId()));
}
SendMessage.remove(String.valueOf(tms.getMessageId())); // message
} }

参考 Spring定时任务的几种实现

 

Spring 学习 5- task 定时任务的更多相关文章

  1. Spring task定时任务执行一段时间后莫名其妙停止的问题

    前因: 我写了一个小项目,主要功能是用Spring task定时任务每天定时给用户发送邮件.执行了几个月一直没有问题,前几天,莫名其妙的突然不再发送邮件了. 只好花费一些时间来查看到底是什么原因造成的 ...

  2. Spring Task定时任务的配置和使用详解

    spring中使用定时任务 1.基于xml配置文件使用定时任务 首先配置spring开启定时任务 <beans xmlns="http://www.springframework.or ...

  3. SpringBoot定时任务 - Spring自带的定时任务是如何实现的?有何注意点?

    通过前文我们基本梳理了定时任务体系:Timer和ScheduledExecutorService是JDK内置的定时任务方案,以及Netty内部基于时间轮实现的HashedWheelTimer,再到Qu ...

  4. spring注解scheduled实现定时任务

    只想说,spring注解scheduled实现定时任务使用真的非常简单. 一.配置spring.xml文件 1.在beans加入xmlns:task="http://www.springfr ...

  5. Spring Boot(九):定时任务

    Spring Boot(九):定时任务 一.pom包配置 pom包里面只需要引入springboot starter包即可 <dependencies> <dependency> ...

  6. 品Spring:关于@Scheduled定时任务的思考与探索,结果尴尬了

    非Spring风格的代码与Spring的结合 现在的开发都是基于Spring的,所有的依赖都有Spring管理,这没有问题. 但是要突然写一些非Spring风格的代码时,可能会很不习惯,如果还要和Sp ...

  7. spring的Scheduled(定时任务)和多线程

    一.前言 在我们日常的开发中,经常用到数据同步的更新,这时我们采用的是spring的定时任务和java的多线程进行数据的更新,进行时实的服务调用. 二.实现思路            1.创建线程类 ...

  8. spring 学习之 bean 的注入方式 property和constructor-arg的使用方式

    spring 学习之 bean 的注入方式 property和constructor-arg的使用方式. bean的注入方式: property 注入是: 通过setxx方法注入. construct ...

  9. Spring学习之AOP总结帖

    AOP(面向方面编程),也可称为面向切面编程,是一种编程范式,提供从另一个角度来考虑程序结构从而完善面向对象编程(OOP). 在进行 OOP 开发时,都是基于对组件(比如类)进行开发,然后对组件进行组 ...

  10. Spring学习之第一个AOP程序

    IOC和AOP是Spring的两大基石,AOP(面向方面编程),也可称为面向切面编程,是一种编程范式,提供从另一个角度来考虑程序结构从而完善面向对象编程(OOP). 在进行 OOP 开发时,都是基于对 ...

随机推荐

  1. nodejs fastdfs

    node端fastdfs客户端上传文件 var FdfsClient = require('fdfs'); var fdfs = new FdfsClient({ // tracker servers ...

  2. C#的Dispose模式复习

    http://www.cnblogs.com/DebugLZQ/archive/2012/08/28/2659189.html http://www.cnblogs.com/tsoukw/archiv ...

  3. 20155321 2016-2017-2《Java程序设计》课堂实践项目2

    20155321 2016-2017-2<Java程序设计>课堂实践项目2 实践内容 编写MyCP.java 实现类似Linux下cp XXX1 XXX2的功能,要求MyCP支持两个参数: ...

  4. 任务队列和异步接口的正确打开方式(.NET Core版本)

    任务队列和异步接口的正确打开方式 什么是异步接口? Asynchronous Operations Certain types of operations might require processi ...

  5. arcpy示范教学(一):基本操作

    arcpy基本操作 打开目录,遍历目录,打开要素类,遍历要素,打开文件,写入属性值 import arcpy import codecs # 设置工作目录 arcpy.env.workspace = ...

  6. mysql学习----支持Emoji表情

    但发现了一个问题,iPhone上有Emoji表情,插入Mysql时失败了,报如下异常: java.sql.SQLException: Incorrect string value: '\xF0\x9F ...

  7. 时序数据库InfluxDB

    在系统服务部署过后,线上运行服务的稳定性是系统好坏的重要体现,监控系统状态至关重要,经过调研了解,时序数据库influxDB在此方面表现优异. influxDB介绍 时间序列数据是以时间字段为每行数据 ...

  8. object-fix/object-position

    今日浏览某大神的一篇博文时发现如下写法: .container > div > img { width: 100%; height: 100%; object-fit: cover; } ...

  9. 《More Effective C++》读书笔记(零)Basic 基础条款

    这是篇读书笔记,只记录自己的理解和总结,一般情况不对其举例子具体说明,因为那正是书本身做的事情,我的笔记作为梳理和复习之用,划重点.我推荐学C++的人都好好读一遍Effective C++ 系列,真是 ...

  10. openvpn部署

    原文发表于cu:2016-03-29 参考文档: 安装:http://qicheng0211.blog.51cto.com/3958621/1575273 安装:http://www.ipython. ...