public static void main(String[] args) {
Timer timer = new Timer();
int iSeconds = 15 * 60;// 秒数
final int[] iCount = {0};// 持续运行次数
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println("任务执行时间: " + System.currentTimeMillis());
// 在这里编写/调用要重复执行的任务代码
MainFunction();
try {
Thread.sleep(100);// 睡眠100ms保证输出语句顺序不会错乱
iCount[0]++;
// 获取当前日期和时间
LocalDateTime currentDateTime = LocalDateTime.now();
// 定义日期时间格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 格式化日期时间
String formattedDateTime = currentDateTime.format(formatter);
System.out.println("当前日期时间: " + formattedDateTime);
System.out.println("===============已运行【" + iCount[0] + "】次===============");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
// 设置任务计划,每隔iSeconds秒执行一次任务,period:毫秒
timer.schedule(task, 0, iSeconds * 1000);
}
在上面的Java代码中,iCount被声明为一个数组 int[],并且包含一个元素,用于在匿名内部类中进行修改。这是因为在Java中,匿名内部类(如TimerTask的实例)只能访问被声明为final的外部变量,或者实际上是被隐式声明为final的变量。
通过将iCount声明为一个包含一个元素的数组,实际上是在绕过了这个限制。虽然数组本身是final的,但是数组中的元素可以被修改。这样就可以在匿名内部类中对iCount的值进行递增操作,而不会遇到编译错误。
这种技巧在匿名内部类中经常被使用,以允许对外部变量进行修改,同时又遵循了Java对final变量的限制。