I have a win form, where I have a block of code which keeps checking for entry in database, every say 2mins. Now I want to avoid using timer control, for performance reason; can the same be achieved using background worker?
Create a new thread and than
While True
CallTheDB()
Thread.Sleep(120000)
End While
Related
I am currently working on an android music app which needs to call an api to get the link of album-art and put it in slider, after 'x' seconds I have to call another api and get an url of advertisement and load it on slider. And then after 'y' seconds I have to repeat the whole process.
What is the best way to implement it without having memory leakage issue. I am currently using 'https://github.com/daimajia/AndroidImageSlider' this slider.
To be more specific, let's say I have two functions, I need to call both periodically after '12' and '3' seconds, how can I implement it.
you can achieve this by using postDelayed()
final Handler h = new Handler();
h.postDelayed (() -> {
//your code here
}, DELAY_TIME);
I need to create a thread in titanium to due some work in background. I have searched around in google and found this:
var queue = Ti.Async.createQueue();
var job = queue.dispatch(function() {
});
But now i don't now how to keep the thread alive (if this is a thread) after the first execution and how due I set the delay for each execution?
I personally use another method to create "background processes" in titanium.
I create a javascript file containing the elements i need to run in background, and apply a "setInterval" to it (to make it run endlessly), like this:
//FILENAME: bgTask.js
function myFunc() {
//Code here
}
setInterval(myFunc, <time in milliseconds>);
Now, i create the controller without view to get it running. For instance, if i need it to run in background in the entire app, i run an "Alloy.createController" in "index.js", but never get the view or show it. This creates and executes the controller in the background.
In "index.js" i use
Alloy.createController("bgTask");
to create the background process.
In case you want to have the background process only run a single time (or a definite number of times) you can change the background process file (bgTask.js in this case) to follow your needs, and create the controller every time you need to run the task.
To get the result from the background process, you can use global variables or any other method you see fit. To use global variables, use
Ti.App.<varname> = <something>
This way the value gets saved for the entire application.
Works for iOS, Android and Windows Phone.
Sorry for the late answer, hope this helped.
So I have this view that moves throughout different views that I have. I tried moving it using a new thread but I got "Can't access View from a different thread than it was created on", so I was like, "whatever just move it to the main thread then". So, I currently have runOnUiThread(this) (The class implements Runnable).
Now, it says:
Skipped x frames! The application may be doing too much work on its main thread.
I googled for a loophole and found that I can use a Handler to do this, which I was able to follow until it was talking about implementing a task. They used a task called PhotoTask and not knowing what it was or where it came from, I just got lost.
So can somebody either explain the Task or tell me another potential way around this?
Code that's causing the error (Note there are more if statements, but they're all the same on the inside as this one:
while (lackees[i].getTileX() < lackees[i].getDestX()
&& lackees[i].getTileY() < lackees[i]
.getDestY()) {
lackees[i].setTileX(lackees[i].getTileX() + 1);
lackees[i].setTileY(lackees[i].getTileY() + 1);
getTileAt(0, lackees[i].getTileX() - 1,
lackees[i].getTileY() - 1).removeView(
lackees[i]);
getTileAt(0, lackees[i].getTileX(),
lackees[i].getTileY()).addView(lackees[i]);
Progress Update #1:
It seems that wait() is better to use then Thread.sleep() but I still get frames lost, just not as many.
Your question is not very clear.
What do you mean by "So I have this view that moves throughout different views that I have".
Handler are mainly used to communicate between 2 threads.
PhotoTask in given link is simply an object/model used to send message from 1 thread to another via Handler.
If you want to update a view, you need to do this in main/UI thread alone. If you want to do some UI update from a separate thread you need to inform the default UI thread handler by passing the operation to be done as a separate runnable instance via runOnUiThread/ view.post/ handler.post.
I can clarify on how to use shared views without using any handler or thread if this is what you need.
I am using Async task to populate auto-complete suggestions from server.
Problem:
when user types and removes the text in edittext so many times.
lets say he typed: cofee > cof > coffee >coffee late .... etc for so many times.
for each text changed after 3 keyword(threshold) i am initializing an asynctask and ask for result.
so in current scenario i have so many threads running in background. so some of my latest async threads are waiting for there chance.
Whole this make my app very slow.
What can I do to tackle this problem?
If it is possible to load entire data from server at beginning...then you can avoid calling asynctask repeatedly and fetching the data from server. This will improve performance of you app. If data displayed in Listview is String, following link show how to filter it:
http://www.androidhive.info/2012/09/android-adding-search-functionality-to-listview/
And if custom object is used in ListView adapter, try:
Filtering ListView with custom (object) adapter
Hopefully this helps.
You should cancel the current task before issuing a new one. Use AsyncTask#cancel(true) for that and make sure that the execution of the task can be quickly stopped. This means correct handling of interruption and frequent checking whether the task was cancelled in the body of AsyncTask#doInBackground.
And you cannot execute again the AsyncTask you have cancelled. You have to create a new one. (Trying to execute it again leads to IllegalStateExceptions)
It worked for me by cancelling the task each time you change the text (if it is still running).
You need to define your request once outside the listener(private for the class), and then start your listener function by (if your request is not finished, then cancel it).
define your request out side the function
private YourSearchTaskClass YourTaskReq = new YourSearchTaskClass();
then start your addTextChangeListener/afterTextChanged by this
if (YourTaskReq.getStatus()!= AsyncTask.Status.FINISHED)
YourTaskAvReq.cancel(false);
YourTaskReq= new YourSearchTaskClass(keyword);
I'm just curious about whether there are times in which I should choose an Executor over a HandlerThread. Are there times that one is superior over the other, or should I really just stick with the HandlerThread? In my case, I'm currently listening to a ServerSocket for connections, and handling each request on a separate thread created by an Executor. Even though I gave a specific example, I'm really just looking for cases in which one is more appropriate than the other. However, I welcome comments about my design.
The Executor class is more powerful and can use a pool of threads, whereas each Handler references a single thread. The Executor allows you to get all the scheduled tasks and cancel them if you'd like. The Handler on the other hand will not answer simple questions such as, how many tasks are waiting or give me a reference to all waiting tasks. I believe one reason that the Handler is more limited is because Android gives you access to the main Handler it uses for the UI and you could really screw up the OS if you started canceling OS tasks.
In general if you need a pool of threads or lots of power use the Executor. If you just need a nice background thread to run one task at a time use a Handler. As an example when I want to query my database I only really want one query to occur at a time and I don't want to generate an ANR so I use a Handler running on a background thread to run my queries.
I believe your choice of executor sounds appropriate since you want to handle multiple incoming requests simultaneously and a Handler can only do one at a time.
UPDATE: How to create a Handler that runs on a background thread:
In your constructor or onCreate write the following, obviously you can set the priority to whatever you like:
public class MyClass {
private Handler mBgHandler;
public MyClass() {
HandlerThread bgThread = new HandlerThread("My-Background-Handler");
bgThread.start();
mBgHandler = new Handler(bgThread.getLooper());
}
}
UPDATE: Don't forget to quit() or quitSafely() your HandlerThread when you are done with it otherwise it will remain waiting forever
I wouldn't follow the sample code in satur9nine's answer as of 2011-Dec-22.
Thread.MIN_PRIOROTY is mapped to android.os.Process.THREAD_PRIORITY_LOWEST. Quote:
Lowest available thread priority. Only for those who really, really don't want to run if anything else is happening.
I would at least use android.os.Process.THREAD_PRIORITY_BACKGROUND, like so:
HandlerThread bgThread = new HandlerThread("handler name");
Process.setThreadPriority(bgThread.getThreadId(), Process.THREAD_PRIORITY_BACKGROUND);
bgThread.start();
mBgHandler = new Handler(bgThread.getLooper());
This assigns the default Android background priority to the thread.
Currently, threads of priority Process.THREAD_PRIORITY_BACKGROUND and lower share an artificially limited amount of CPU time by means of a Linux cgroup, see for example here. If a background task does not just wait for I/O but performs real computations, I'd consider increasing its priority by android.os.Process.THREAD_PRIORITY_MORE_FAVORABLE which (currently) moves it out of the background cgroup while still not substantially endangering UI and real time activities.
Update: satur9nine's answer was silently revised on 2013-Jan-08 to not set the lowest possible priority any more. The HandlerThread will now implicitly have a priority of android.os.Process.THREAD_PRIORITY_BACKGROUND. This means that it now gets the default background task priority but it is still limited to consume an artificial maximum of 10% CPU time along with all another background tasks which may exist. If that's not desired, use my code above e.g. with
Process.setThreadPriority(bgThread.getThreadId(),
Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
to lift your background thread out of the cgroup.