zl程序教程

您现在的位置是:首页 >  后端

当前栏目

如何在JAVA中每隔一段时间执行一段程序

JAVA执行程序 如何 一段 一段时间 每隔
2023-09-27 14:21:31 时间
可以用线程来做,每隔几秒开一个线程
代码如下
	public void runTask() {
		final long timeInterval = 120000;// 两分钟运行一次
		final ThreadService threadService = new ThreadService();
		Runnable runnable = new Runnable() {
			public void run() {
				while (true) {
					// ------- code for task to run
//你要运行的程序
					// ------- ends here
					try {
						Thread.sleep(timeInterval);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		Thread thread = new Thread(runnable);
		thread.start();
	}