Jcrontab 根據 數據源(存儲任務定義的介質)分為四類:
crontab 文本文件)events 表)Crontab.newTask())核心配置文件 jcrontab.properties 指定數據源類型、日誌、刷新頻率等。
JCrontabApp.java // 主啟動類,支持命令行參數切換數據源
NumTest.java // 測試任務:每分鐘打印時間與計數
LetterTest.java // 測試任務:每分鐘打印 Hello World
jcrontab.properties // 核心配置
crontab / crontab.xml // 任務定義文件
org.jcrontab.data.file = crontab
org.jcrontab.data.datasource = org.jcrontab.data.FileSource
org.jcrontab.Crontab.refreshFrequency = 3
* * * * * com.aweb.test.NumTest
* * * * * com.aweb.test.LetterTest
java -cp ... com.aweb.test.JCrontabApp jcrontab.properties filedata
使用 Jcrontab 提供的 SQL 創建 events 表(含 seconds、minutes、class_name、method、parameters 等字段)。
org.jcrontab.data.datasource = org.jcrontab.data.GenericSQLSource
org.jcrontab.data.GenericSQLSource.driver = org.gjt.mm.mysql.Driver
org.jcrontab.data.GenericSQLSource.url = jdbc:mysql://127.0.0.1/netbook
org.jcrontab.data.GenericSQLSource.username = root
org.jcrontab.data.GenericSQLSource.password =
java ... JCrontabApp jcrontab.properties database
程序啟動時將任務寫入 events 表,隨後輪詢執行。
org.jcrontab.data.file = crontab.xml
org.xml.sax.driver = org.apache.xerces.parsers.SAXParser
org.jcrontab.data.datasource = org.jcrontab.data.XMLSource
<?xml version="1.0" encoding="GB2312"?>
<CRONTAB>
<CRONTABENTRY id="0">
<SECONDS>0</SECONDS>
<MINUTES>*</MINUTES>
<CLASS>com.aweb.test.NumTest</CLASS>
<METHOD>main</METHOD>
</CRONTABENTRY>
<CRONTABENTRY id="2">
<CLASS>org.jcrontab.NativeExec</CLASS>
<METHOD>main</METHOD>
<PARAMETERS>net send 192.168.0.109 "你好!"</PARAMETERS>
</CRONTABENTRY>
</CRONTAB>
利用內置 org.jcrontab.NativeExec,XML 中配置 PARAMETERS 即可定時執行系統命令(如 ping、net send、shell 腳本)。
org.jcrontab.SendMail.to = yourname@sohu.com
org.jcrontab.SendMail.from = myname@sohu.com
org.jcrontab.SendMail.smtp.host = smtp.sohu.com
org.jcrontab.SendMail.smtp.username = yourname
org.jcrontab.SendMail.smtp.password = password
註:郵件功能受 SMTP 服務器策略影響,需實測調試。
String[] params = {"arg1", "arg2"};
cron.newTask("org.jcrontab.NativeExec", "main", params);
Crontab:單例調度器,init()/uninit() 控制生命周期ConnectionThread:每個客戶連接一個線程(WebServer 示例中)CrontabParser / CrontabEntryBean / CrontabEntryDAO:數據庫模式下的解析與持久化ShutdownHook:優雅關閉,等待運行中任務完成NativeExec 橋接外部命令,SendMail 實現告警通知