用Java写一段代码每隔1秒调用一次方法
时间: 2024-01-30 08:03:41 浏览: 29
可以使用Java的Timer和TimerTask来实现每隔1秒调用一次方法的功能,示例代码如下:
```java
import java.util.Timer;
import java.util.TimerTask;
public class TimerDemo {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
// 调用需要执行的方法
doSomething();
}
};
// 每隔1秒执行一次任务
timer.schedule(task, 0, 1000);
}
private static void doSomething() {
System.out.println("Hello World!");
}
}
```
在上面的示例代码中,我们创建了一个Timer对象和一个TimerTask对象,然后使用Timer的schedule方法来设置任务的执行时间和间隔时间。在任务执行时,会调用doSomething方法来执行需要完成的操作。这样就实现了每隔1秒调用一次方法的功能。
相关问题
java 实现每隔一段时间调用一个异步线程任务
在Java中,您可以使用`java.util.Timer`和`java.util.TimerTask`类来实现定时器功能,然后在定时器到期时启动您的异步任务。以下是一个示例代码:
```java
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CompletableFuture;
public class MyAsyncTask extends TimerTask {
@Override
public void run() {
// 异步任务代码
CompletableFuture.runAsync(() -> {
// 异步任务代码
});
}
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new MyAsyncTask(), 0, 5000); // 每隔5秒钟启动一次异步任务
}
}
```
在这个例子中,`MyAsyncTask`类继承自`TimerTask`类,并实现了`run()`方法来执行异步任务。然后,在`main()`方法中,您可以创建一个`Timer`对象并调用`schedule()`方法来启动定时器。第一个参数是您的`TimerTask`实例,第二个参数是延迟启动的时间(以毫秒为单位),第三个参数是定时器的周期(以毫秒为单位)。在这里,我们设置周期为5000毫秒,即每隔5秒钟启动一次异步任务。
用java写一段每隔一分钟访问百度的请求,超过十分钟自动停止
```
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
public class BaiduRequester {
private static final String BAIDU_URL = "https://www.baidu.com/";
private static final int TIMEOUT = 5000;
private static final int INTERVAL = 60000;
private static final int MAX_TIME = 10;
private int count = 0;
private Timer timer;
public void start() {
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
count++;
if (count > MAX_TIME) {
stop();
} else {
try {
URL url = new URL(BAIDU_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(TIMEOUT);
connection.setReadTimeout(TIMEOUT);
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
System.out.println("Successfully accessed " + BAIDU_URL);
} else {
System.out.println("Failed to access " + BAIDU_URL + ", response code: " + responseCode);
}
connection.disconnect();
} catch (IOException e) {
System.out.println("Failed to access " + BAIDU_URL + ": " + e.getMessage());
}
}
}
}, 0, INTERVAL);
}
public void stop() {
if (timer != null) {
timer.cancel();
System.out.println("Stopped accessing " + BAIDU_URL);
}
}
public static void main(String[] args) {
BaiduRequester requester = new BaiduRequester();
requester.start();
}
}
```
使用Timer和TimerTask实现每隔一分钟访问百度一次,并且超过十分钟后自动停止访问。在每次访问时,使用Java的HttpURLConnection发送GET请求,最后输出访问结果。如果超过十分钟,调用stop方法停止定时器。