我需要在预定义的时间内运行一些代码,当时间到了需要停止时.目前我正在使用TimerTask来允许代码执行一段时间,但这会导致代码创建无穷无尽的线程,而这只是效率不高.还有更好的选择吗?
当前代码;
// Calculate the new lines to draw
Timer timer3 = new Timer();
timer3.schedule(new TimerTask(){
public void run(){
ArrayList<String> Coords = new ArrayList<String>();
int x = Float.valueOf(lastFour[0]).intValue();
int y = Float.valueOf(lastFour[1]).intValue();
int x1 = Float.valueOf(lastFour[2]).intValue();
int y1 = Float.valueOf(lastFour[3]).intValue();
//Could be the wrong way round (x1,y1,x,y)?
Coords = CoordFiller.coordFillCalc(x, y, x1, y1);
String newCoOrds = "";
for (int j = 0; j < Coords.size(); j++)
{
newCoOrds += Coords.get(j) + " ";
}
newCoOrds.trim();
ClientStorage.storeAmmendedMotion(newCoOrds);
}
}
,time);
Run Code Online (Sandbox Code Playgroud) 我正在使用Timer和TimerTask来长时间轮询聊天应用程序的新消息.我想研究两种"略微"不同的可能性:
1:计时器声明为局部变量
public List<MessageBean> getLastMessages(...) {
[...]
Timer timer = new Timer(true); //**Timer declared as local variable**
while (someCondiction) {
MessagesTimerTask returnMessagesTask = new MessagesTimerTask([...]);
timer.schedule(returnMessagesTask, 6000);
synchronized (listMessageBean) {
listMessageBean.wait();
//notify is called in the MessagesTimerTask which extends TimerTask
}
}
}
Run Code Online (Sandbox Code Playgroud)
*问题:每次调用方法时,我都会看到创建了一个新线程,[Timer-1],[Timer-2]等.在Eclipse Debug窗口中,即使在getLastMessages之后它们似乎都在运行(..)完成运行并将值返回给客户端.如果计时器实际上使用线程,这可能会导致巨大的问题,并且在很少的事务之后,服务器最终会消耗所有的机器资源.
2:定时器声明为本地字段
private final Timer timer = new Timer(true); //**Timer declared as local field**
public List<MessageBean> getLastMessages(...) {
[...]
while (someCondiction) {
MessagesTimerTask returnMessagesTask = new MessagesTimerTask([...]);
timer.schedule(returnMessagesTask, …
Run Code Online (Sandbox Code Playgroud) 我是Java的新手,我正在尝试生成一个每5到10秒运行一次的任务,所以在5到10之间的任何时间间隔,包括10.
我尝试了几件事但到目前为止没有任何工作.我最近的努力如下:
timer= new Timer();
Random generator = new Random();
int interval;
//The task will run after 10 seconds for the first time:
timer.schedule(task, 10000);
//Wait for the first execution of the task to finish:
try {
sleep(10000);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
//Afterwards, run it every 5 to 10 seconds, until a condition becomes true:
while(!some_condition)){
interval = (generator.nextInt(6)+5)*1000;
timer.schedule(task,interval);
try {
sleep(interval);
} catch(InterruptedException ex) {
ex.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
"任务"是一个TimerTask.我得到的是:
Exception in thread "Thread-4" java.lang.IllegalStateException: Task already …
Run Code Online (Sandbox Code Playgroud) 在android中有一些刷新处理选项,如Timer,TimerTask,ScheduledExecutorService,AlarmManager和Handler.这是最好的方法.
有人检查过上述方法的资源利用率吗?我在这里列出了上述方法的实现.
使用Handler重复执行任务
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
new MyScheduledTask.execute(param);
}
}, TimeInterval);
Run Code Online (Sandbox Code Playgroud)
使用Timer重复执行任务
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
synchronized public void run() {
new MyScheduledTask.execute(param);
}
}}, 10000, 10000);
Run Code Online (Sandbox Code Playgroud)
使用ScheduledExecutorService重复激活任务
ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate
(new Runnable() {
public void run() {
new MyScheduledTask.execute(param);
}
}, 0, 10, TimeInterval);
Run Code Online (Sandbox Code Playgroud)
使用Timer和TimerTask重复执行任务
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(),1, TimeInterval);
class UpdateTimeTask extends TimerTask {
public void run()
{ …
Run Code Online (Sandbox Code Playgroud) 我正在实现ServletContextListener,以便在我的应用服务器(GlassFish 3.1)上安排各种作业.我正在使用contextInitialized()
安排重复任务,并 contextDestroyed()
调用清理方法,如关闭c3p0:
public class JobScheduler implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
//schedule TimerTasks
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
//cancel TimerTasks
//cleanup methods
}
}
Run Code Online (Sandbox Code Playgroud)
当我取消TimerTask
s时,我添加了逻辑,等待任何正在运行的任务在继续之前完成,以确保在清理资源时没有任何内容仍在执行.
回答我的问题:当我取消部署我的应用程序时,我看到GlassFish输出中显示了其中一个或两个警告:
WARNING: Input stream has been finalized or forced closed without being explicitly closed; stream instantiation reported in following stack trace
java.lang.Throwable
at com.sun.enterprise.loader.ASURLClassLoader$SentinelInputStream.<init>(ASURLClassLoader.java:1230)
at com.sun.enterprise.loader.ASURLClassLoader$InternalJarURLConnection.getInputStream(ASURLClassLoader.java:1338)
at sun.misc.URLClassPath$Loader.getResource(URLClassPath.java:503)
at sun.misc.URLClassPath.getResource(URLClassPath.java:169)
at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at …
Run Code Online (Sandbox Code Playgroud) 不知何故它不起作用,据我说它应该是这样的:
public void Splash(){
Timer timer= new Timer();
timer.schedule(new TimerTask(){
MexGame.this.runOnUiThread(new Runnable() {
public void run(){
SplashImage.setImageDrawable(aktieknop);
} //Closes run()
}); //Closes runOnUiThread((){})
},SplashTime); //Closes the Timeratask((){})
} //closes Splash()
Run Code Online (Sandbox Code Playgroud)
有人知道我错过了什么吗?
正式评论 我知道愚蠢的问题,或者我正在做一些不可能的事情,但我尝试了所有合乎逻辑的可能性.所以可能遗漏了一些东西,或者我正在尝试做一些不可能的事情.你能帮帮我吗?我正在尝试使用以下代码,但这会产生令牌问题:
Timer timer= new Timer();
timer.schedule(new TimerTask(){
runOnUiThread(new Runnable() {
public void run(){
SplashImage.setImageDrawable(aktieknop);}
});}
},SplashTime);
Run Code Online (Sandbox Code Playgroud)
如果我阻止了runOnUiThread,它会崩溃,因为我正在尝试从另一个线程调整UI,但至少没有令牌问题,任何人都有任何想法?:
Timer timer= new Timer();
timer.schedule(new TimerTask(){
// runOnUiThread(new Runnable() {
public void run(){
SplashImage.setImageDrawable(aktieknop);}
// });}
},SplashTime);
Run Code Online (Sandbox Code Playgroud) android punctuation runnable timertask android-runonuithread
我需要定期从服务器获取新闻/事件更新,例如我的Android应用中每20分钟一次.AFAIK Intent Service和Broadcast Receiver组合将比使用Service更好.因为我不打算与正在运行的服务进行通信.为了定期获取事件,我知道2个选项
1)使用Timer Task ScheduleAtFixedRate,我将启动IntentService,它将获取事件一次并广播(如果有任何更新)并自行销毁.在给定Interval之后,TimerTask将再次触发IntentService
2)简单地在app的开头和Intent Service中启动Intent Service onHandleIntent方法启动TimerTask ScheduleAtFixedRate.如果这是首选方式,我何时以及何时取消计时器任务以及何时意图服务将被销毁.
或者我必须使用Alarm Manager.注意我需要这些更新,只要我使用应用程序,我也需要每20到30分钟更新一次,而不是每1或3分钟更新一次.
任何身体请建议我,在此先感谢.
在onCreate,我运行一个每分钟都重复的任务.我在这里是怎么做到的:
myTimer = new Timer();
int delay = 30000; // delay for 30 sec.
int period = 600000; // repeat every 60 sec.
doThis = new TimerTask() {
public void run() {
Log.v("TImer","repeated");
wv.reload();
}
};
myTimer.scheduleAtFixedRate(doThis, delay, period);
Run Code Online (Sandbox Code Playgroud)
所有代码都在onCreate中.因此,当应用程序从屏幕上关闭时,我可以在logcat中看到计时器钢块运行,并且除非应用程序被销毁,否则不会停止.所以,在onPause
我打电话的活动中,myTimer.cancel();
但它没有帮助.即使应用程序不在屏幕上,我仍然可以在logcat中看到更新.那么,如何阻止timerTask
?
package name.cpr;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.Timer;
import java.util.TimerTask;
public class ExampleActivity extends ActionBarActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
Timer timer = new Timer();
timer.schedule(new CheckConnection(), 0, 3000);
ImageView iv = (ImageView) findViewById(R.id.imageView);
iv.setVisibility(View.VISIBLE);
}
class CheckConnection extends TimerTask{
public void run(){
ImageView iv = (ImageView) findViewById(R.id.imageView);
iv.setVisibility(View.INVISIBLE); //<- Unfortunatly Error Here
}
}
}
Run Code Online (Sandbox Code Playgroud)
启动应用程序,第一次图像视图可见性工作,但计时器不工作,如果计时器启动相同的错误不幸....已经停止
我开始开发一个记录视频的Android应用程序,我需要每1分钟收集一次GPS位置
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(id.camera_preview);
preview.addView(mPreview);
private boolean isRecording = false;
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isRecording) {
// stop recording and release camera
mMediaRecorder.stop(); …
Run Code Online (Sandbox Code Playgroud) timertask ×10
android ×6
java ×5
timer ×4
alarmmanager ×2
chat ×1
glassfish-3 ×1
guava ×1
handler ×1
imageview ×1
livechat ×1
punctuation ×1
random ×1
runnable ×1
service ×1
visibility ×1