dojo class(spring quartz为什么tomcat启动后没有马上执行)

本文目录
- spring quartz为什么tomcat启动后没有马上执行
- 如何使用 Gridx
- arcgis api for javascript开发时,显示dojo未定义,怎么办
- 用英语介绍长沙旅游景点作文 关于去长沙旅游的作文英语
- Spring定时任务为什么没有执行
spring quartz为什么tomcat启动后没有马上执行
Spring定时任务的几种实现
博客分类:
spring框架
quartzspringspring-task定时任务注解
Spring定时任务的几种实现
近日项目开发中需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息,借此机会整理了一下定时任务的几种实现方式,由于项目采用spring框架,所以我都将结合
spring框架来介绍。
一.分类
从实现的技术上来分类,目前主要有三种技术(或者说有三种产品):
Java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务。使用这种方式可以让你的程序按照某一个频度执行,但不能在指定时间运行。一般用的较少,这篇文章将不做详细介绍。
使用Quartz,这是一个功能比较强大的的调度器,可以让你的程序在指定时间执行,也可以按照某一个频度执行,配置起来稍显复杂,稍后会详细介绍。
Spring3.0以后自带的task,可以将它看成一个轻量级的Quartz,而且使用起来比Quartz简单许多,稍后会介绍。
从作业类的继承方式来讲,可以分为两类:
作业类需要继承自特定的作业类基类,如Quartz中需要继承自org.springframework.scheduling.quartz.QuartzJobBean;java.util.Timer中需要继承自java.util.TimerTask。
作业类即普通的java类,不需要继承自任何基类。
注:个人推荐使用第二种方式,因为这样所以的类都是普通类,不需要事先区别对待。
从任务调度的触发时机来分,这里主要是针对作业使用的触发器,主要有以下两种:
每隔指定时间则触发一次,在Quartz中对应的触发器为:org.springframework.scheduling.quartz.SimpleTriggerBean
每到指定时间则触发一次,在Quartz中对应的调度器为:org.springframework.scheduling.quartz.CronTriggerBean
注:并非每种任务都可以使用这两种触发器,如java.util.TimerTask任务就只能使用第一种。Quartz和spring task都可以支持这两种触发条件。
二.用法说明
详细介绍每种任务调度工具的使用方式,包括Quartz和spring task两种。
Quartz
第一种,作业类继承自特定的基类:org.springframework.scheduling.quartz.QuartzJobBean。
第一步:定义作业类
Java代码
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class Job1 extends QuartzJobBean {
private int timeout;
private static int i = 0;
//调度工厂实例化后,经过timeout时间开始执行调度
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* 要调度的具体任务
*/
@Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {
System.out.println("定时任务执行中…");
}
}
第二步:spring配置文件中配置作业类JobDetailBean
Xml代码
说明:org.springframework.scheduling.quartz.JobDetailBean有两个属性,jobClass属性即我们在java代码中定义的任务类,jobDataAsMap属性即该任务类中需要注入的属性值。
第三步:配置作业调度的触发方式(触发器)
Quartz的作业触发器有两种,分别是
org.springframework.scheduling.quartz.SimpleTriggerBean
org.springframework.scheduling.quartz.CronTriggerBean
第一种SimpleTriggerBean,只支持按照一定频度调用任务,如每隔30分钟运行一次。
配置方式如下:
Xml代码
第二种CronTriggerBean,支持到指定时间运行一次,如每天12:00运行一次等。
配置方式如下:
Xml代码
关于cronExpression表达式的语法参见附录。
第四步:配置调度工厂
Xml代码
说明:该参数指定的就是之前配置的触发器的名字。
第五步:启动你的应用即可,即将工程部署至tomcat或其他容器。
第二种,作业类不继承特定基类。
Spring能够支持这种方式,归功于两个类:
org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean
org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean
这两个类分别对应spring支持的两种实现任务调度的方式,即前文提到到java自带的timer task方式和Quartz方式。这里我只写MethodInvokingJobDetailFactoryBean的用法,使用该类的好处是,我们的任 务类不再需要继承自任何类,而是普通的pojo。
第一步:编写任务类
Java代码
public class Job2 {
public void doJob2() {
System.out.println("不继承QuartzJobBean方式-调度进行中...");
}
}
可以看出,这就是一个普通的类,并且有一个方法。
第二步:配置作业类
Xml代码
《bean id="job2"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"》
说明:这一步是关键步骤,声明一个MethodInvokingJobDetailFactoryBean,有两个关键属性:targetObject指定任务类,targetMethod指定运行的方法。往下的步骤就与方法一相同了,为了完整,同样贴出。
第三步:配置作业调度的触发方式(触发器)
Quartz的作业触发器有两种,分别是
org.springframework.scheduling.quartz.SimpleTriggerBean
org.springframework.scheduling.quartz.CronTriggerBean
第一种SimpleTriggerBean,只支持按照一定频度调用任务,如每隔30分钟运行一次。
配置方式如下:
Xml代码
如何使用 Gridx
创建 Gridx
Gridx 继承了 dijit._WidgetBase,因此其创建方式和其他 widget 类似,只是有一些必须指定的参数需要特别说明。
选用合适的 store 和 cache
Gridx 与 DataGrid 一样,都以 Dojo 的 store 作为数据源。不过,Gridx 需要用户指出所用的 store 是异步的还是同步的。异步 store 通常由服务器端提供数据,向它请求数据时往往需要异步地接收返回数据;而同步 store 的所有数据一般都在客户端,因此所有的请求都能同步完成。异步 store 往往会带来更为复杂的逻辑,因此 Gridx 针对这两种 store 分别进行了优化。但由于无法从 store 本身得知它是否异步,同时为了减小代码量,用户需要将这个信息告知 Gridx。告知的方法是设置 cacheClass 参数:
清单 1. 创建 Gridx 并配置 cacheClass 参数
require([
"gridx/Grid",
"gridx/core/model/cache/Sync",
......
"dojo/domReady!"
], function(Gridx, Cache, ......){
......
var grid = new Gridx({
cacheClass: Cache
store: store,
......
});
grid.placeAt(’gridContainerNode’);
grid.startup();
});目前 Gridx 有两种 cache 实现:gridx/core/model/cache/Sync 和 gridx/core/model/cache/Async,前者用于同步 store,后者用于异步 store。Async 的实现逻辑比 Sync 要复杂得多,这是因为它需要考虑数据的延迟加载。这样,如果用户的应用只需要客户端数据,就完全不必用到关于延迟加载的代码,从而减小了最终下载到浏览器的代码量。
cacheClass 既可以直接接受 cache 实现的构造函数(如上例),也可以接受 MID,例如:
清单 2. 用 MID 设置 cacheClass 参数
var grid = new Gridx({
cacheClass: "gridx/core/model/cache/Async"
......
});这种写法更适合以 HTML 声明的方式创建 Gridx 的场合,因为它不需要引入额外的变量。
目前 Gridx 能够直接支持 dojo(x)/data/* 的老 store 以及 dojo/store/* 的新 store,而不需要任何适配转换。常用的同步 store 有 dojo/data/ItemFileWriteStore 以及 dojo/store/Memory。常用的异步 store 有 dojox/data/JsonRestStore、dojox/data/QueryReadStore 以及 dojo/store/JsonRest。
需要特别注意的是,Gridx 要求 store 中的数据行必须具有唯一标识符(ID)。对于老 store 而言,也就是必须要实现 dojo/data/api/Identity。所幸刚才列举的常用 store 都满足这个要求。
声明列
配好 store 并选择好 cache 之后,就需要声明 Gridx 的列结构。列声明使用 structure 参数,这和 DataGrid 类似。所不同的是,Gridx 的列声明结构非常简单,只支持一维数组,没有 DataGrid 中视图(View)和子行(rows/cells)等复杂的声明结构:
清单 3. 一维数组结构的列声明
var grid = new Gridx({
cacheClass: Cache
store: store,
structure: [
{id: ’column1’, ......},
{id: ’column2’, ......},
{id: ’column3’, ......},
......
]
});下面各小节详细介绍列声明中各个属性的含义。
id、name、field
对于 Gridx 来说,每一列都有一个唯一标识符(ID)。用户最好能指定一些有意义的 ID,从而方便以后的使用。如果用户没有指定,那么 Gridx 会分别赋予"1", "2", "3", ....... 等字符串类型的自然数作为列的默认 ID。
与 DataGrid 类似,name 属性是指表头上显示出来的列名。name 属性可以是任意字符串,甚至可以包含 HTML 标签,从而做出各种定制效果。例如:{id: ’column1’, name: ’《b》Company 《i》Name《/i》《/b》’}。
field 属性也是从 DataGrid 沿袭下来的,指该列在 store 中的对应域。该列中的单元格会从这个 field 域中取得数据。
图 1. name 属性作为普通字符串、未指定、以及带 HTML/CSS 的各种情况
formatter 函数
Gridx 的 formatter 函数与 DataGrid 中的同名函数不同,其目的在于为 Gridx 提供数据,而不是对数据做显示上的修饰。如果某一列没有 field 参数,就可以通过 formatter 函数来提供数据,例如:
清单 4. 使用 formatter 函数组合多个域的数据
{id: ’column1’, formatter: function(rawData){
return rawData.field1 + rawData.field2;
});这样,这一列就能显示两个数据域的和。
图 2. formatter 函数综合多个数据域的内容产生了 Summary 列中的数据
formatter 函数所传入的 rawData 参数是以 store 的 field 名称作为 key 的关联数组(对象),包含当前行中的所有数据,形如:
清单 5. rawData 格式
rawData: {
field1: data1,
field2: data2,
......
}这种形式要比某些 store(主要是老 store)的数据项(item)更容易使用,也使接口与新 store 保持一致。
decorator 函数
Gridx 对数据的产生和数据的修饰做了严格的区分。formatter 是用于产生数据,decorator 函数则用于修饰数据。例如:
清单 6. 用 decorator 函数为单元格添加 HTML/CSS
{id: ’column1’, field: ’field1’,
decorator: function(cellData, rowId, rowIndex){
return "《a href=’www.google.com?q=" + cellData + "’》《b》" +
cellData + "《/b》《/a》";
}
}这样就能在单元格中显示出链接。
图 3. 使用 decorator 对数据做修饰
decorator 函数只能返回字符串,不像 DataGrid 的 formatter 函数还可以返回 widget 实例。关于如何在单元格中显示 widget 的问题将在其他文章中详细介绍。
style 和 class
通过在 decorator 函数中加入 HTML 标签和 style 属性可以对单元格中的内容做各种修饰,但无法改变单元格本身的样式。要做到这一点,需要 style 或 class:
清单 7. 字符串形式的 style 和 class 参数
{id: ’column1’, field: ’field1’,
style: ’text-align: center;’,
’class’: ’mySpecialColumn’
}style 和 class 都会直接加入到 《TD》 标签的 style 属性和 class 属性。
style 和 class 还可以写成一个返回字符串的函数,这样单元格的样式就能随数据而变化:
清单 8. 函数形式的 style 和 class 参数
{id: ’column1’, field: ’field1’,
style: function(cell){
return cell.data() % 2 ? ’color: red;’ : ’color: blue;’;
},
’class’: function(cell){
return cell.data() %2 ? ’oddClass’ : ’evenClass’;
}
}这里 style 和 class 函数所传入的 cell 参数代表了当前所处理的单元格,可以通过各种方便的方法获取有关该单元格的一切信息。
图 4. 使用 style 函数为每一个单元格设置独特背景色的例子
配置功能模块
有了 store、cacheClass 和 structure 后,Gridx 就能运行了。不过这样的 Gridx 除了显示数据之外,几乎没有任何界面功能。Gridx 几乎所有的功能都是由可选模块(module)实现的,需要在创建时声明使用了那些模块。这提供了巨大的灵活性来满足各种不同的需求。
声明模块的是 modules 属性:
清单 9. 通过 modules 参数配置功能模块
require([
"gridx/Grid",
"gridx/core/model/cache/Sync",
"gridx/modules/VirtualVScroller",
"gridx/modules/ColumnResizer",
"gridx/modules/Focus",
"gridx/modules/SingleSort",
......
dojo/domReady!"
], function(Gridx, Cache, VirtualVScroller, ColumnResizer, Focus, SingleSort, ......){
......
var grid = new Gridx({
cacheClass: Cache
store: store,
structure: structure,
vScrollerLazy: true,// 模块参数可作为 Gridx 参数传递
modules: [
VirtualVScroller, // 用法 1:直接列举模块构造函数
"gridx/modules/ColumnResizer", // 用法 2:模块 MID
{ // 用法 3:带有 moduleClass 的对象
moduleClass: SingleSort,
initialOrder: { colId: ’column1’, descending: true }
},
{ // 用法 4: moduleClass 也接受 MID
moduleClass: "gridx/modules/Focus"
}
]
});
......
});从上面的例子可见,要使用一个模块先要引入该模块的文件,然后直接列举在 modules 数组中即可。modules 数组中的模块既可以是模块构造函数本身,也可以是模块的 MID,还可以是一个含有 moduleClass 属性的对象。模块本身也可能有参数,这些参数既可以与 moduleClass 一起放在一个对象里(如 initialOrder),也可以直接作为 Gridx 的参数,只不过需要加上所属模块的名称作为前缀(如 vScrollerLazy,这里 vScroller 是模块名称,lazy 是属性名,加上前缀后首字母大写)。模块参数直接作为 Gridx 参数可以使代码更为简洁,因此是推荐的配置方法。
上面的例子中加入了 4 个模块:VirtualVScroller 实现了延迟渲染的功能,每次只渲染出需要显示的行,从而可以很快地完成拥有大量数据的 Grid 的创建;ColumnResizer 实现了鼠标拖动改变列宽的功能;SingleSort 是一个单列排序的简单实现;Focus 模块则是对键盘的支持,这是一个被许多其他模块引用的模块,对于 A11y 非常重要。
熟悉 DataGrid 的用户会发现这些功能在 DataGrid 中都是默认自带的。虽然这些功能很常用,但用户在不需要它们的时候却难以屏蔽;即使能够屏蔽它们的功能,大量的有关这些功能的代码也依旧存在,而这不失为一种浪费。
arcgis api for javascript开发时,显示dojo未定义,怎么办
没有引用dojo的类库,你只引了arcgis的类库。
明显你的arcgis要与dojo集成的,首先在引arcgis之前引用dojo.js
《script type="text/javascript" src="js/dojo/dojo/dojo.js"》《/script》 你的dojo放在哪儿,你自己找吧。
用英语介绍长沙旅游景点作文 关于去长沙旅游的作文英语
!!急!!!介绍长沙的旅游胜地,天气,小吃,等等的英语作文
Traffic management conditions is the regional tourism industry formation and development basis, and the accessibility, the degree and road quality fit and unfit quality, to attract tourists, line organization, the construction of tourism environment and so on, have extremely profound. If there is no perfect traffic management network system support, and even if the abundant tourism resources can only stay in a state of development, can’t make full use of its tourism value, the development of regional tourism industry will be severely restricted.
Mount wudang good location conditions, resources are unique, Taoism culture details profound, as the world cultural heritage, Taoism culture, the wudang mountain development potential is great. However tourist traffic management means lag but restricted tourism industry of the development of a huge bottleneck. In order to improve the tourism resources of accessibility, improve its real as a world cultural heritage in the class, to wudang mountain tourist traffic management recognition of is very necessary. 1 tourism resources evaluation
Mount wudang has incomparable beauty, is beautiful and harmonious unity of humanity beauty height, known as the "everlasting unique scenic spot, the first one seazan".
(1) the natural landscape strange beautiful mount wudang. Here, there are 72 He fold the incredible peak, 36 rocks, 24 jian, the 11 holes, 10 stone, such as channel 9 wonderful scenery. The tianzhufeng known as "YiZhuQingTian expensive"; The main peak around all the various and a strange, but strove for supremacy toward the form made in heaven, "WanShanLai toward the" wonders. Mount wudang variety of scenery, no matter when the four seasons can enjoy visit the mysterious empty spirit of natural beauty.
(2) wudang Taoism majestic buildings. Here is the birthplace of Taoist zhenwu tati, built of ancient Taoism on a grand scale, the momentum of the majestic, known as the "the wonders." only According to statistics, tang dynasty to qing dynasty monastic build temples in more than 500, over 20000 rooms. In the Ming dynasty, emperor of mount wudang dojo the heyday as a royal family shrine, with nine palace 9 view on 33 place complex. Existing ancient building is in good in 129, still do not break when the grand manner.
(3) wudang Taoism culture has a long history. In addition to the mount wudang Taoism building, the Taoist martial arts, Taoism, Taoism FaShi, Taoism medicinal food, Taoism and precious cultural relics and so on also become famous at home and abroad, especially in the wudang boxing is enjoy extensive international reputation. In addition, the wudang relevant zhenwu and legend story, customs and so on also rich and colorful, which had its.
2 tourism traffic management present situation analysis
2.1 tourism traffic management situation
(1) highway traffic. For the development of tourism, the wudang mountain road transportation need in recent years have been relatively substantially improved. , 316 national highway (han ten road), 209 national highway wear condition, han ten highway shiyan to xiangfan section has been opened, initially forming a "ten" glyph communication network. Wuhan to shiyan, shiyan to yinchuan of highway under construction and perfect, will further improve the wudang mountain, mount wudang tourist traffic to promote the development of tourism. The wudang mountain scenic area traffic: send to the whole country or way of wudang mount bus to Beijing, shijiazhuang north, zhengzhou; West to hanzhong, ankang, xian; East to nanjing and wuxi, south of changsha, shenzhen, etc. The province is more traffic extend in all directions.
我只知道这些了,不好意思
关于介绍长沙的英语作文 60-80字
关于介绍长沙的英语作文
Changsha is rich in tourist resources because of its unique geographical location.Surrounding the city are the beautiful Yuelu MountainDawei Mountain and Weishan Mountainand the Xiangjiang River and Liuyang River flow across it.
The Juzizhou scenic spot in the city is regarded as one of the eight most charming places in Hunan attracting both domestic and overseas visitors.
译文
长沙地理位置得天独厚,旅游资源丰富,美丽的岳麓山、大围山、巍山环绕,湘江、浏阳河横穿其间。
该市橘子洲风景区被认为是湖南吸引国内外游客的八大最具魅力的地方之一。
初三英语作文长沙旅游
Trafficmanagementconditionsistheregionaltourismindustryformationanddevelopmentbasis,andtheaccessibility,thedegreeandroadqualityfitandunfitquality,toattracttourists,lineorganization,theconstructionoftourismenvironmentandsoon,haveextremelyprofound.Ifthereisnoperfecttrafficmanagementnetworksystemsupport,andeveniftheabundanttourismresourcescanonlystayinastateofdevelopment,can’tmakefulluseofitstourismvalue,thedevelopmentofregionaltourismindustrywillbeseverelyrestricted.Mountwudanggoodlocationconditions,resourcesareunique,Taoismculturedetailsprofound,astheworldculturalheritage,Taoismculture,thewudangmountaindevelopmentpotentialisgreat.Howevertouristtrafficmanagementmeanslagbutrestrictedtourismindustryofthedevelopmentofahugebottleneck.Inordertoimprovethetourismresourcesofaccessibility,improveitsrealasaworldculturalheritageintheclass,towudangmountaintouristtrafficmanagementrecognitionofisverynecessary.1tourismresourcesevaluationMountwudanghasincomparablebeauty,isbeautifulandharmoniousunityofhumanitybeautyheight,knownasthe"everlastinguniquescenicspot,thefirstoneseazan".(1)thenaturallandscapestrangebeautifulmountwudang.Here,thereare72Hefoldtheincrediblepeak,36rocks,24jian,the11holes,10stone,suchaschannel9wonderfulscenery.Thetianzhufengknownas"YiZhuQingTianexpensive";Themainpeakaroundallthevariousandastrange,butstroveforsupremacytowardtheformmadeinheaven,"WanShanLaitowardthe"wonders.Mountwudangvarietyofscenery,nomatterwhenthefourseasonscanenjoyvisitthemysteriousemptyspiritofnaturalbeauty.(2)wudangTaoismmajesticbuildings.HereisthebirthplaceofTaoistzhenwutati,builtofancientTaoismonagrandscale,themomentumofthemajestic,knownasthe"thewonders."onlyAccordingtostatistics,tangdynastytoqingdynastymonasticbuildtemplesinmorethan500,over20000rooms.IntheMingdynasty,emperorofmountwudangdojotheheydayasaroyalfamilyshrine,withninepalace9viewon33placecomplex.Existingancientbuildingisingoodin129,stilldonotbreakwhenthegrandmanner.(3)wudangTaoismculturehasalonghistory.InadditiontothemountwudangTaoismbuilding,theTaoistmartialarts,Taoism,TaoismFaShi,Taoismmedicinalfood,Taoismandpreciousculturalrelicsandsoonalsobecomefamousathomeandabroad,especiallyinthewudangboxingisenjoyextensiveinternationalreputation.Inaddition,thewudangrelevantzhenwuandlegendstory,customsandsoonalsorichandcolorful,whichhadits.2tourismtrafficmanagementpresentsituationanalysis2.1tourismtrafficmanagementsituation(1)highwaytraffic.Forthedevelopmentoftourism,thewudangmountainroadtransportationneedinrecentyearshavebeenrelativelysubstantiallyimproved.,316nationalhighway(hantenroad),209nationalhighwaywearcondition,hantenhighwayshiyantoxiangfansectionhasbeenopened,initiallyforminga"ten"glyphcommunicationnetwork.Wuhantoshiyan,shiyantoyinchuanofhighwayunderconstructionandperfect,willfurtherimprovethewudangmountain,mountwudangtouristtraffictopromotethedevelopmentoftourism.Thewudangmountainscenicareatraffic:sendtothewholecountryorwayofwudangmountbustoBeijing,shijiazhuangnorth,zhengzhou;Westtohanzhong,ankang,xian;Easttonanjingandwuxi,southofchangsha,shenzhen,etc.Theprovinceismoretrafficextendinalldirections.我只知道这些了,不好意思
一篇向外国友人介绍长沙风景名胜的中考英语作文,60字左右
Normally I have fun and a good time. During the work days I study in the classes, and during the weekends, I play with my friends happily.
But sometimes I will feel blue and really worried about this or that, for example, the result of an examination, or whether an event owned by me will go on smoothly.
My family never made me feel uncomfortable or crazy. They only cared about my condition and majority of the time they cared too much (if you know what i mean).
Hard time in life will put our relationship’s foundation to the test. We must be realistic in life, but do not loose faith in the person we love. Every chapter in life as an end, this will too. I regret time, education, and faith in God will help those foundations in our relationships hold firm till the storm is over.
介绍长沙旅游胜地 小吃等 的英语作文
就是地方特产嘛我没去过长沙所以介绍个小吃就行看Traffic management conditions is the regional tourism industry formation and development basis, and the accessibility, the degree and road quality fit and unfit quality, to attract tourists, line organization, the construction of tourism environment and so on, have extremely profound. If there is no perfect traffic management network system support, and even if the abundant tourism resources can only stay in a state of development, can’t make full use of its tourism value, the development of regional tourism industry will be severely restricted.
Mount wudang good location conditions, resources are unique, Taoism culture details profound, as the world cultural heritage, Taoism culture, the wudang mountain development potential is great. However tourist traffic management means lag but restricted tourism industry of the development of a huge bottleneck. In order to improve the tourism resources of accessibility, improve its real as a world cultural heritage in the class, to wudang mountain tourist traffic management recognition of is very necessary. 1 tourism resources evaluation
Mount wudang has incomparable beauty, is beautiful and harmonious unity of humanity beauty height, known as the "everlasting unique scenic spot, the first one seazan".
(1) the natural landscape strange beautiful mount wudang. Here, there are 72 He fold the incredible peak, 36 rocks, 24 jian, the 11 holes, 10 stone, such as channel 9 wonderful scenery. The tianzhufeng known as "YiZhuQingTian expensive"; The main peak around all the v
Spring定时任务为什么没有执行
Spring定时任务的几种实现
博客分类:
spring框架
quartzspringspring-task定时任务注解
Spring定时任务的几种实现
近日项目开发中需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息,借此机会整理了一下定时任务的几种实现方式,由于项目采用spring框架,所以我都将结合
spring框架来介绍。
一.分类
从实现的技术上来分类,目前主要有三种技术(或者说有三种产品):
Java自带的java.util.Timer类,这个类允许你调度一个java.util.TimerTask任务。使用这种方式可以让你的程序按照某一个频度执行,但不能在指定时间运行。一般用的较少,这篇文章将不做详细介绍。
使用Quartz,这是一个功能比较强大的的调度器,可以让你的程序在指定时间执行,也可以按照某一个频度执行,配置起来稍显复杂,稍后会详细介绍。
Spring3.0以后自带的task,可以将它看成一个轻量级的Quartz,而且使用起来比Quartz简单许多,稍后会介绍。
从作业类的继承方式来讲,可以分为两类:
作业类需要继承自特定的作业类基类,如Quartz中需要继承自org.springframework.scheduling.quartz.QuartzJobBean;java.util.Timer中需要继承自java.util.TimerTask。
作业类即普通的java类,不需要继承自任何基类。
注:个人推荐使用第二种方式,因为这样所以的类都是普通类,不需要事先区别对待。
从任务调度的触发时机来分,这里主要是针对作业使用的触发器,主要有以下两种:
每隔指定时间则触发一次,在Quartz中对应的触发器为:org.springframework.scheduling.quartz.SimpleTriggerBean
每到指定时间则触发一次,在Quartz中对应的调度器为:org.springframework.scheduling.quartz.CronTriggerBean
注:并非每种任务都可以使用这两种触发器,如java.util.TimerTask任务就只能使用第一种。Quartz和spring task都可以支持这两种触发条件。
二.用法说明
详细介绍每种任务调度工具的使用方式,包括Quartz和spring task两种。
Quartz
第一种,作业类继承自特定的基类:org.springframework.scheduling.quartz.QuartzJobBean。
第一步:定义作业类
Java代码
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
public class Job1 extends QuartzJobBean {
private int timeout;
private static int i = 0;
//调度工厂实例化后,经过timeout时间开始执行调度
public void setTimeout(int timeout) {
this.timeout = timeout;
}
/**
* 要调度的具体任务
*/
@Override
protected void executeInternal(JobExecutionContext context)
throws JobExecutionException {
System.out.println("定时任务执行中…");
}
}
第二步:spring配置文件中配置作业类JobDetailBean
Xml代码
《bean name="job1" class="org.springframework.scheduling.quartz.JobDetailBean"》
《property name="jobClass" value="com.gy.Job1" /》
《property name="jobDataAsMap"》
《map》
《entry key="timeout" value="0" /》
《/map》
《/property》
《/bean》
说明:org.springframework.scheduling.quartz.JobDetailBean有两个属性,jobClass属性即我们在java代码中定义的任务类,jobDataAsMap属性即该任务类中需要注入的属性值。
第三步:配置作业调度的触发方式(触发器)
Quartz的作业触发器有两种,分别是
org.springframework.scheduling.quartz.SimpleTriggerBean
org.springframework.scheduling.quartz.CronTriggerBean
第一种SimpleTriggerBean,只支持按照一定频度调用任务,如每隔30分钟运行一次。
配置方式如下:
Xml代码
《bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"》
《property name="jobDetail" ref="job1" /》
《property name="startDelay" value="0" /》《!-- 调度工厂实例化后,经过0秒开始执行调度 --》
《property name="repeatInterval" value="2000" /》《!-- 每2秒调度一次 --》
《/bean》
第二种CronTriggerBean,支持到指定时间运行一次,如每天12:00运行一次等。
配置方式如下:
Xml代码
《bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"》
《property name="jobDetail" ref="job1" /》
《!—每天12:00运行一次 --》
《property name="cronExpression" value="0 0 12 * * ?" /》
《/bean》
关于cronExpression表达式的语法参见附录。
第四步:配置调度工厂
Xml代码
《bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"》
《property name="triggers"》
《list》
《ref bean="cronTrigger" /》
《/list》
《/property》
《/bean》
说明:该参数指定的就是之前配置的触发器的名字。
第五步:启动你的应用即可,即将工程部署至tomcat或其他容器。
第二种,作业类不继承特定基类。
Spring能够支持这种方式,归功于两个类:
org.springframework.scheduling.timer.MethodInvokingTimerTaskFactoryBean
org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean
这两个类分别对应spring支持的两种实现任务调度的方式,即前文提到到java自带的timer task方式和Quartz方式。这里我只写MethodInvokingJobDetailFactoryBean的用法,使用该类的好处是,我们的任 务类不再需要继承自任何类,而是普通的pojo。
第一步:编写任务类
Java代码
public class Job2 {
public void doJob2() {
System.out.println("不继承QuartzJobBean方式-调度进行中...");
}
}
可以看出,这就是一个普通的类,并且有一个方法。
第二步:配置作业类
Xml代码
《bean id="job2"
class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"》
《property name="targetObject"》
《bean class="com.gy.Job2" /》
《/property》
《property name="targetMethod" value="doJob2" /》
《property name="concurrent" value="false" /》《!-- 作业不并发调度 --》
《/bean》
说明:这一步是关键步骤,声明一个MethodInvokingJobDetailFactoryBean,有两个关键属性:targetObject指定任务类,targetMethod指定运行的方法。往下的步骤就与方法一相同了,为了完整,同样贴出。
第三步:配置作业调度的触发方式(触发器)
Quartz的作业触发器有两种,分别是
org.springframework.scheduling.quartz.SimpleTriggerBean
org.springframework.scheduling.quartz.CronTriggerBean
第一种SimpleTriggerBean,只支持按照一定频度调用任务,如每隔30分钟运行一次。
配置方式如下:
Xml代码
《bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"》
《property name="jobDetail" ref="job2" /》
《property name="startDelay" value="0" /》《!-- 调度工厂实例化后,经过0秒开始执行调度 --》
《property name="repeatInterval" value="2000" /》《!-- 每2秒调度一次 --》
《/bean》
第二种CronTriggerBean,支持到指定时间运行一次,如每天12:00运行一次等。
配置方式如下:
Xml代码
《bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"》
《property name="jobDetail" ref="job2" /》
《!—每天12:00运行一次 --》
《property name="cronExpression" value="0 0 12 * * ?" /》
《/bean》
以上两种调度方式根据实际情况,任选一种即可。
第四步:配置调度工厂
Xml代码
《bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"》
《property name="triggers"》
《list》
《ref bean="cronTrigger" /》
《/list》
《/property》
《/bean》
说明:该参数指定的就是之前配置的触发器的名字。
第五步:启动你的应用即可,即将工程部署至tomcat或其他容器。
到此,spring中Quartz的基本配置就介绍完了,当然了,使用之前,要导入相应的spring的包与Quartz的包,这些就不消多说了。
其实可以看出Quartz的配置看上去还是挺复杂的,没有办法,因为Quartz其实是个重量级的工具,如果我们只是想简单的执行几个简单的定时任务,有没有更简单的工具,有!
请看我第下文Spring task的介绍。
Spring-Task
上节介绍了在Spring 中使用Quartz,本文介绍Spring3.0以后自主开发的定时任务工具,spring task,可以将它比作一个轻量级的Quartz,而且使用起来很简单,除spring相关的包外不需要额外的包,而且支持注解和配置文件两种
形式,下面将分别介绍这两种方式。
第一种:配置文件方式
第一步:编写作业类
即普通的pojo,如下:
Java代码
import org.springframework.stereotype.Service;
@Service
public class TaskJob {
public void job1() {
System.out.println(“任务进行中。。。”);
}
}
第二步:在spring配置文件头中添加命名空间及描述
Xml代码
《beans xmlns="/schema/beans"
xmlns:task="/schema/task"
。。。。。。
xsi:schemaLocation="/schema/task h
k.org/schema/task/spring-task-3.0.xsd"》
第三步:spring配置文件中设置具体的任务
Xml代码
《task:scheduled-tasks》
《task:scheduled ref="taskJob" method="job1" cron="0 * * * * ?"/》
《/task:scheduled-tasks》
《context:component-scan base-package=" com.gy.mytask " /》
说明:ref参数指定的即任务类,method指定的即需要运行的方法,cron及cronExpression表达式,具体写法这里不介绍了,详情见上篇文章附录。
《context:component-scan base-package="com.gy.mytask" /》这个配置不消多说了,spring扫描注解用的。
到这里配置就完成了,是不是很简单。
第二种:使用注解形式
也许我们不想每写一个任务类还要在xml文件中配置下,我们可以使用注解@Scheduled,我们看看源文件中该注解的定义:
Java代码
@Target({java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scheduled
{
public abstract String cron();
public abstract long fixedDelay();
public abstract long fixedRate();
}
可以看出该注解有三个方法或者叫参数,分别表示的意思是:
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
Java代码
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component(“taskJob”)
public class TaskJob {
@Scheduled(cron = "0 0 3 * * ?")
public void job1() {
System.out.println(“任务进行中。。。”);
}
}
第二步:添加task相关的配置:
Xml代码
《context:annotation-config /》
《!—spring扫描注解的配置 --》
《context:component-scan base-package="com.gy.mytask" /》
《!—开启这个配置,spring才能识别@Scheduled注解 --》
《task:annotation-driven scheduler="qbScheduler" mode="proxy"/》
《task:scheduler id="qbScheduler" pool-size="10"/》
说明:理论上只需要加上《task:annotation-driven /》这句配置就可以了,这些参数都不是必须的。
Ok配置完毕,当然spring task还有很多参数,我就不一一解释了,具体参考xsd文档schema/task/spring-task-3.0.xsd。
附录:
cronExpression的配置说明,具体使用以及参数请百度google
字段 允许值 允许的特殊字符
秒 0-59 , - * /
分 0-59 , - * /
小时 0-23 , - * /
日期 1-31 , - * ? / L W C
月份 1-12 或者 JAN-DEC , - * /
星期 1-7 或者 SUN-SAT , - * ? / L C #
年(可选) 留空, 1970-2099 , - * /
- 区间
* 通配符
? 你不想设置那个字段
下面只例出几个式子
CRON表达式 含义
"0 0 12 * * ?" 每天中午十二点触发
"0 15 10 ? * *" 每天早上10:15触发
"0 15 10 * * ?" 每天早上10:15触发
"0 15 10 * * ? *" 每天早上10:15触发
"0 15 10 * * ? 2005" 2005年的每天早上10:15触发
"0 * 14 * * ?" 每天从下午2点开始到2点59分每分钟一次触发
"0 0/5 14 * * ?" 每天从下午2点开始到2:55分结束每5分钟一次触发
"0 0/5 14,18 * * ?" 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发
"0 0-5 14 * * ?" 每天14:00至14:05每分钟一次触发
"0 10,44 14 ? 3 WED" 三月的每周三的14:10和14:44触发
"0 15 10 ? * MON-FRI" 每个周一、周二、周三、周四、周五的10:15触发

更多文章:
全球新冠肺炎疫情背景下航运发展(盐田港复苏日志:半年历劫从“低谷”到“爆仓” 疫情之后巨轮如何越洋航行)
2026年9月7日 17:10
matlab求解带字母参数方程组(我想matlab求一个关于x,y的方程组 ab c d f e h m n 都是参数)
2026年9月7日 16:30
oracle中的循环语句(下面哪个不是oracle程序设计中的循环语句 a for)
2026年9月7日 15:30
电脑里2个系统怎么删除一个(电脑开机显示有两个系统,如何删除一个)
2026年9月7日 12:20
scrollthrough意思(“scroll”是什么意思)
2026年9月7日 08:00
怎么激活keygen(注册机如何激活cad2008一个简单激活cad2008的方法)
2026年9月7日 06:30
vba编写excel插件(excel vba中能否动态创建控件)
2026年9月7日 04:40





