我有以下问题。每2秒,程序将进入一个if语句。在这个if语句中,我希望有一个定时器,在15秒后给我一条消息。计时器应在延迟1秒的情况下运行。但是,当我与计时器“等待”时,if语句将再执行7次。我的问题是,我总是同时运行7个相同的TimerTask。我该如何解决这个问题?
if (response == true) {
final Timer timer = new Timer();
final int keepAliveTimeout = 15000; //15 seconds
timer.schedule(new TimerTask() {
@Override
我试图每隔三秒运行一次java.util.Timer,在特定条件下,我需要将它再延迟2。为了检查是否可以使用Thread.sleep()实现这一点,我编写了下面的代码。
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
if (true) { //When this is false timer should continue at 3 second interval.
try {
Threa
大家好。我开发了下面的代码。其目的是:每500毫秒在屏幕上打印一次当前时间。这应该发生在线程内。我的代码不起作用,我也不知道为什么。
====================================================================
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class MyTimer implements Runnable
{
public class PrintingTask extends
如果我将定时器设置为每3秒执行一次代码。如果代码没有在3秒内完成,会发生什么?计算机将终止代码或等待代码结束或继续计时器,并与未完成的代码并发执行代码。
如果计算机将与未完成的代码并发执行代码,那么如果方法中涉及变量会发生什么情况。例如,run的第一行可能是i--,但最后一行是i++。如果它并发运行,当未完成的代码仍在运行,但新的运行周期开始时,新的运行周期将添加i值,因此当前一个周期运行到最后一行时,i值是否会出错(因为新的运行周期在前一个代码完成之前执行i-- )。如果是,如何避免?
int delay = 0; // delay for 0 sec.
int period = 300
我有以下while循环:
while (keepRunning) {
if (!once) {
// Run a test method every 30th second
// Run the new calculations from the database
new CalculatorDriver().run();
// Wait in the while loop for 1 second before looping again
TimeUnit.SECONDS.sleep(1);
....
public class mainClass {
public mainClass(){
Timer time = new Timer();
mainClass.calculate calculate = new mainClass.calculate();
time.schedule(calculate, 1 * 1000);
}
public static void main(String[] args){
new mainClass();
}
class calcula
我开发这个应用程序是为了在用户给定的时间内关闭/重新启动和休眠计算机。我已经附上了一张应用程序的图片,developing.User可以选择小时、分钟或秒来关闭/重新启动计算机,或者在用户给出的时间内使计算机休眠。我已经附加了我正在使用的代码示例,但是它没有计算时间
public void cal() {
int seconds = (int) jSpinner1.getValue();
int minutes = (int) jSpinner2.getValue();
int hours = (int) jSpinner3.getValue();
int S
我一直在使用服务来每3秒运行我的代码。在我的情况下,有办法每3秒运行一次24小时吗?我的代码看起来像这样。它所做的并不重要,所以我已经把它全部删除了。我唯一关心的部分是一个List<String>,原因是在这24小时之后,我想用这个列表做更多的事情。
public static void main(String[] args) throws Exception {
ScheduledExecutorService ses = Executors.newScheduledThreadPool(2);
ses.scheduleWithFixedDelay(new Run