介紹:
crontab是一個linux下的定時執行工具,可以在無需人工干預的情況下運行作業。crontab 是Linux的內置服務,可以用以下的方法啓動、關閉這個服務:
/sbin/service crond start //啓動服務/sbin/service crond stop //關閉服務
/sbin/service crond restart //重啓服務
/sbin/service crond reload //重新載入配置
/sbin/service crond status // 查看運行狀態
1.新建maven項目“Monitor”
2.新建測試類與main方法
package com.monitor.test;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Date;
public class Monitor {
public static void main(String[] args) throws Exception {
File file = new File("/home/users/test.txt");
FileWriter fw = new FileWriter(file, true);
PrintWriter pw = new PrintWriter(fw);
pw.println("追加內容,date:" + new Date());
pw.flush();
fw.flush();
pw.close();
fw.close();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Monitor</groupId>
<artifactId>Monitor</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<finalName>Monitor</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<!-- main方法所在類-->
<mainClass>com.monitor.test.Monitor</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>
jar-with-dependencies
</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
4.打包
mvn -Dmaven.test.skip=true package
5.上傳*jar-with-dependencies.jar到服務器
6.運行crontab -e 編輯定時器
加入: */1 * * * * /usr/local/java/jdk1.8/bin/java -jar /home/users/Monitor-jar-with-dependencies.jar
並保存
定時器示例:
5 * * * *每小時第5分鐘執行
*/5 * * * *每5分鐘執行
0 2 * * * 每天凌晨2點執行
7.觀察users/目錄下是否生成test.txt並每分鐘寫入內容