我正在尝试在指定的时间(即每隔几秒钟)异步重复执行任务(即从文本文件加载数据),尽管此速率可能会在运行时发生变化).
我做了一些研究,并决定这需要一个AsyncTask或一个单独的线程.为了简单起见,我决定使用AsyncTask.
我现在需要根据重复的计时器计划执行此AsyncTask.我相信我必须使用Timer和TimerTask.
下面的代码是我想要实现的简单形式.当我尝试使用Android模拟器(通过Eclipse IDE)运行此代码时,我收到以下消息:"抱歉!应用程序意外停止.请再试一次."
我想知道问题出在哪里以及如何解决问题.谢谢!
public class Sample extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SimpleTimerTask myTimerTask = new SimpleTimerTask();
long delay = 0;
long period = 5000;
Timer myTimer = new Timer();
myTimer.schedule(myTimerTask, delay, period);
}
private class SimpleAsyncTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... params) {
return null;
}
}
private class SimpleTimerTask extends TimerTask {
public void run() {
new SimpleAsyncTask().execute();
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:这是似乎相关的LogCat消息
致命异常:Timer-0
java.lang.ExceptionInInitializerError
在 ...
引起:java.lang.RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序
在 …
我一直在经历很多问题尝试暂停和取消暂停计时器,如果我将方向锁定为纵向或横向它可以工作,但这不完全是我想要做的.当然,当您更改方向时会调用onCreate方法,因此我取消了我的timertask并将其设置为null,但是在多次运行方向后,它不再取消时间任务.我在这里查看了其他人的问题,但似乎没有人能够回答我的问题.继承我的代码.它现在有点草率,因为我一直在努力让我能够让它发挥作用.
public class singleTimer extends Activity implements OnClickListener {
private Integer setTime = 0;
private Integer tmrSeconds = 0;
private Integer tmrMilliSeconds = 0;
private Timer myTimer = new Timer();
private TimerTask myTimerTask;
private TextView timerText;
private boolean isPaused = true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_timer);
Bundle extras = getIntent().getExtras();
setTime = extras.getInt("com.bv.armyprt.timer_duration");
if (myTimerTask != null) {
myTimerTask.cancel();
myTimerTask = null;
}
if (savedInstanceState != null) {
if (savedInstanceState.getInt("tmrSeconds") == 0) {
tmrSeconds = setTime;
} …
Run Code Online (Sandbox Code Playgroud) 我有一个MediaPlayer
播放本地音频文件的对象.我TimerTask
在播放音频时使用a 来更新SeekBar的位置和TextView上的文本.
有一个按钮.当用户按下按钮时音频开始.当他们第二次按下它时音频停止.当他们第三次按下它再次开始播放时,应用程序会因错误而崩溃
'causedby: TimerTask is scheduled already and InvocationTargetException'.
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
public void onAudioClicked(View v) {
if (mainPlayer == null) {
mainPlayer = MediaPlayer.create(this, R.raw.session1);
// Get audio duration and set textview
int d = mainPlayer.getDuration();
TextView t = (TextView)findViewById(R.id.totalTime);
t.setText(String.format("%d:%d",
TimeUnit.MILLISECONDS.toMinutes(d),
TimeUnit.MILLISECONDS.toSeconds(d) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(d))));
sb.setProgress(0);
sb.setMax(mainPlayer.getDuration());
mainPlayer.start();
timer = new Timer();
timer.schedule(task, 1000);
} else {
mainPlayer.stop();
mainPlayer.release();
mainPlayer = null;
timer.cancel();
task.cancel();
timer = null;
}
}
TimerTask task = new TimerTask(){
public void …
Run Code Online (Sandbox Code Playgroud) 我正在尝试制作一个蛇型游戏,我很难让"颗粒"以固定的间隔出现在随机的地方(我想让它达到10秒).当我在短暂的延迟后运行程序时(1000毫秒),颗粒开始出现在不同位置的屏幕上极快地闪烁.我想要做的是让颗粒每10秒钟在一个随机位置出现一个,而不是快速闪烁.任何帮助,将不胜感激.
PS我之前从未做过这样的事情,如果代码看起来有点粗糙,我会道歉.一般编码的任何建议也非常感谢.
编辑:我知道这仍然是不正确的但我只是想知道我到目前为止是否至少在正确的轨道上.现在,"颗粒"只是坐在框架的右上角.我的计时器或列表现在是否存在问题,或者只是一般的问题.顺便说一句,如果更新我的代码只是为了显示新的问题在这个网站上不受欢迎,请告诉我,我只是在评论部分寻求帮助并停止编辑.
package snake;
import java.awt.* ;
import java.awt.event.*;
import java.util.* ;
import javax.swing.*;
import javax.swing.Timer;
/**
*
* @author Carlos
*/
public class Pellet extends JPanel
{
Random randomNumber = new Random() ;
int x = 0 ;
int y = 0 ;
private Game game ;
private Timer timer ;
private final int DELAY = 100 ;
private ArrayList<Pellet> al = new ArrayList<>() ;
public Pellet(Game game)
{
this.game = game ;
}
@Override
public void paint(Graphics …
Run Code Online (Sandbox Code Playgroud) 在 中和 和 和有什么java.util.Timer.scheduleAtFixedRate(TimerTask timer, long delay, long period)
区别?delay
period
我有一个TimerTask
对象timerTask。我的代码正在运行,但是当服务最初启动时,我的计时器任务会在指定时间(即下午 3:30)之前立即运行,但我希望它每天只在下午 3:30 运行一次。
Calendar cal = Calendar.getInstance();
cal.set(Calendar.AM_PM, Calendar.PM);
cal.set(Calendar.HOUR, 3);
cal.set(Calendar.MINUTE, 30);
cal.set(Calendar.SECOND, 0);
Date date = cal.getTime();
timer.schedule(timerTask, date, 1000*60*60*24); // once per day
Run Code Online (Sandbox Code Playgroud) 在我调用 timer.cancel() 方法后,TimerTask 再运行一次。在调用 stopBusTimer() 方法后,我不需要执行 TimerMethod。
有人可以解释为什么会这样吗?
busTimer = new Timer();
busTimer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod(mSelectedRoute);
}
}, 0, Consts.BUS_TIMER_INTERVAL);
private void stopBusTimer() {
if (busTimer != null) {
busTimer.cancel();
busTimer.purge();
busTimer = null;
Log.v(LOG_TAG, "stop BusTimer");
}
}
Run Code Online (Sandbox Code Playgroud) 我想我不完全了解Timer和TimerTask在Java和Android中的工作方式。现在,我定义了许多定期任务,这些任务要在计时器中安排。
我想知道我应该使用单个计时器来安排任务,还是为每个任务使用不同的计时器实例?计时器有自己的线程吗?预定任务是否在新线程中执行?后台发生了什么?
这些方法之间有什么区别?
方法1的样例代码:
private void initTasks() {
TimerTask task1 = new MyTimerTask1();
TimerTask task2 = new MyTimerTask2();
TimerTask task3 = new MyTimerTask3();
Timer timer = new Timer();
timer.schedule(task1, 0, TASK1_PERIOD);
timer.schedule(task2, 0, TASK2_PERIOD);
timer.schedule(task3, 0, TASK3_PERIOD);
}
class MyTimerTask1 extends TimerTask {
public void run() {
//do task1
}
}
class MyTimerTask2 extends TimerTask {
public void run() {
//do task2
}
}
class MyTimerTask3 extends TimerTask {
public void run() {
//do …
Run Code Online (Sandbox Code Playgroud) 我有一个代码必须在未来的某个日期时间执行,假设我有一个未来的日期,并且我想在未来的该日期 +1 分钟内执行一段代码,但仅限一次。我知道我要使用 java Timer 和 TimerTask 来执行此操作。例如,执行以下操作:
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args) {
Calendar myDate = Calendar.getInstance();
myDate.add(Calendar.MINUTE, 1);
Date afterOneMinute = myDate.getTime();
System.out.println("Scheduled at:" + afterOneMinute);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Executed at:" + (new Date()));
}
}, afterOneMinute);
}
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种使用ScheduledExecutorService进行相同操作的优雅方法,以便拥有一个特定的池,因为该池将用于多个调用。有人可以帮助我吗?
我正在使用 TimerTask 运行 springboot 应用程序,我的服务对象显示为空。
我尝试了各种方法,但无法摆脱空指针异常。
主要类。
@SpringBootApplication
@ComponentScan(basePackages = {"com.comments.demo"})
public class NotifyMain {
@Autowired
static
NotifyService notifyService;
public static void main(String[] args) {
Timer timer1 = new Timer();
timer1.schedule(notifyService, 10, 10);
SpringApplication.run(NotifyMain.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
服务类
package com.comments.demo;
@Service
@Configurable
public class NotifyService extends TimerTask{
@Autowired
ListNotification listElement;
@Override
public void run() {
Notification notification= new Notification();
listElement.add(notification);
}
Run Code Online (Sandbox Code Playgroud)
ListNotification 和 Notification 类工作正常。
安慰
Exception in thread "main" java.lang.NullPointerException
at java.util.Timer.sched(Timer.java:399)
at java.util.Timer.schedule(Timer.java:248)
at com.comments.demo.NotifyMain.main(NotifyMain.java:22)
Run Code Online (Sandbox Code Playgroud)
这是 ListNotification 的代码 …