Scheduling Java threads

Hi, I need a thread to run at say midday and then execute every hour after that. I have tried to read previous problems but cant seem to find the solution i am looking for. Can anyone help?

thanks again, I am still not quite there,
if i open a thread is it like having a continuos
loop?The analogy that a thread is similar to a loop does not appeal to me. I don't think that is a proper comparison. Because if you wanted a thread to run without stop, then you would specify the code something like this:
void run()
     for(;;)
     }//End of infinite for() loop
}//End of run() methodThe thread, when started from the main (or wherever), starts its execution from the run() method, does the work which is specified in the run() method and then stops. It cannot return anything like a normal method. It is not like an infinite loop by itself unless you specify and tell it to be so.
so if i started my program at for example 9.20am i the
program would loop and keep checking until say
midnight when i want the thread to execute, from there
i can just sleep the thread as i have been shown
above, In effect, when you say Thread.sleep(timeInMilliSeconds), you are just making the thread inactive. Don't think of it as an never ending for loop or something like that.
When a thread is made inactive, the CPU is relinquished by the thread and the CPU is used for some other processing. During the time when the thread remains in an inactive stste, it does not get any CPU time. So, it remains suspended, if you want to think of it that way, and once the specified time period elapses, the thread wakes up and is put to a ready state. If the CPU is free to give access to this thread, then the thread starts processing again. That is why you will have to specify the code as follows to catch an InterruptedException...which might be thrown because of CPU access probelms when the thread wakes up and tries to gain CPU time once again:
try
    long time = 18000000L;
    Thread.sleep(time);
catch(InterruptedException ex)
    //Do whatever you wish with the thread
sorry to be a pest :-)Hey no problems :-)
If there is anything at all I will be glad to help. You would have got much better replies and explanations from either xiarcel or warnerja but I guess they are not logged in.
Anyways...I am always happy to help if I can :-)
Vijay :-)

Similar Messages

  • Use java thread? or Oracle DB scheduler?

    I have a java thread which purge records in a table every 30 seconds. The thread calls a prepared statement which is like "delete from MyTable where status=99"
    can I use DB's scheduled job to do the same thing? I can create a DB schedule, and a job in plsql.
    Thus I can save on DB connections.
    Which one is better in terms of performance?

    SoulTech2012 wrote:
    i personally recommend against PL/SQL if you can manage it
    some will argue that it's okay to couple yourself to a database because you're likely not to change it
    but i've seen enough migrations to know the painConversely I have seen attempts to process data by dragging it across the network in the vain attempt to make the application database agnostic. Which results in orders of magnitude more processing time when the application needs to do anything approaching real volume.

  • Calculate elapse time of a Java thread  before execution

    Hi,
    I would like to enquire how can I calculate the elapse time of a Java thread BEFORE this thread is executiing or running.?
    I wish to estimate the elapsed time of each Java thread before execution to better schedule these threads to run on multiple processors for load balancing testing.
    Please help
    -meileng-[                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    You can grab the system time in the initiating thread immediately before calling start(), and as the first step in run() in the new thread.
    However, this measurement is utterly meaningless, as it can vary between architectures or even between consecutive runs on the same box. Furthermore, even once a thread starts, it may do nothing more than that one grab-the-system-time instruction before it get swapped out for a theoretically unbounded amount of time.
    By definition, if you spawn multiple threads in Java, you don't know or care which one get CPU time when, except as you control by syncing, sleep, wait, notify, notifyAll, and whatever control priorities give you. Additionally, you don't know when the OS will give your VM cycles, and on multi-CPU machines, you don't know how many CPUs it will get when it does get cycles.

  • How to assigne Java thread to a specific cpu core

    Hello everyone,
    I want to ask a complicated question. How can I assign Java threads to specific core in a multi-threaded application. The underlyinsg OS can be Linux or Windows. Is there any option provided in JVM can do it?
    If I want to fork a process using C, how can I mix the Java and C together.
    I am looking forward your suggestions.
    Thank you.

    yang2007 wrote:
    Can I fork several Java processes using C and letting each Java process run on a core? These would be questions for a C forum, or one for the OS on which you wish to run this.
    The benefit may be to reduce the interference.You're assuming that you are smarter at thread scheduling than the algorithms written, tested, and honed over decades by people whose job is specifically that.

  • Java Thread Priority

    I am working on a system where I have a couple of background threads processing some non-time critical tasks. The desired behaviour of the system is that the background threads would adapt itself when the load of the system is increasing/descreasing... So as to ensure the normal operation of the system performing the main tasks.
    How reliable is with the use of java thread priority... I thought of something like lowering the priority of the background threads gradually when the load increases and then boosting the priority to a max of NORMAL_PRIORITY when the load descreases... what about the use of yield()? I am using some application facts to predicts the load of the system... Does anybody has a clue whether it is possible to query general information about the system load through some java APIs (without using native libs)?
    Your advice and help is much appreciated...

    It is very platform dependant. Windows screws
    everything up when it comes to threads. They favor
    GUI threads natively over non GUI threads. So instead
    of letting the programmer setup thread priorities
    Microsoft figures your a moron and adjusts it for
    you... Plus the 10 levels of priorities doesn't map
    well at all between unix and Windows. If you look
    even deeper inside you will see just what a joke
    Windows threads are.I don't think I can just rely on the reliability of Java Thread Scheduling... I need something more than that. I need to reach a confidence level that the background threads will not affect the operation of the main worker threads. Though "sleeping" to give up control may not have result in good utilization, but it indirectly create more chances for the worker threads to run. I need to play around with a good sleep time, or best, sleep longer when the load is high/increasing and shorter when the load is low/decreasing... By the way, do u think the context switches incurred when will be significant?

  • Preemption of Java thread (WARNING: Experts only)

    Hi java experts,
    I am thinking about a task scheduler. I would like to create my task scheduler a little bit like a CPU scheduler in such a way that it can support many scheduling algorithms.
    So my task scheduler could be a pool of thread that keep one or many queue(s) of tasks. It seem reasonnable that Task objects implements Runnable but it's not necessary; instead, a Task could be like an event and the TaskScheduler could dispatch a thread to an EventHandler implementing Runnable that will process the task.
    Some scheduling algorithms are easy to implements, like FCFS (First-Come, First-Served). But, others seem very hard to implements because algorithms use preemtion for time-sharing, like RR (Round-Robin).
    Thus, is-it possible to preempt a java thread or simulate this behavior?
    -Jean

    Whatever scheduling algorithm you use
    will depend on the underlying OS scheduling algorithm
    and the restrictions imposed by Java's WORA nature.The JVM schedules threads using a preemptive, priority-based scheduling algorithm. So, if a thread with a higher priority than the thread currently running enters the Runnable state, the JVM preempts the currently running thread and executes the thread with the higher priority. With this in mind, I think that it could be possible to create a TaskScheluer with a preemtive behaviour, maybe by modifying dynamically the threads priority...

  • Java Threads not being released after loggin off

    Hello everyone,
    We are seeing a weird problem in our PI 7.0 box.
    Once I logout from the XI box (both ABAP and Java stck) my basis tem still sees Java threads aginst my id still open. Our system does not seem to be realeasing Java threads.
    Is this a know problem? What are the remidition steps.

    Hi,
    Are there existing HTTP sessions only?
    The following might be helpful.
    http://help.sap.com/saphelp_nw73/helpdata/en/c7/5ee440ba994fa3b187ff2f050cfe7c/content.htm
    http://wiki.sdn.sap.com/wiki/display/ERPHCM/Sessionnotendingafterlogoff
    Regards,
    Varun

  • Java threads monitoring

    I am using Java threads in my Java program, running on Windows Professional 2000. I am monitoring the threads using Windows Performance Monitor (WPM). However, even running a small Java program which creates only 2 threads, results in many (at least 10) instances of Java threads being reported by the WPM. Problem is, in WPM, there is no way to determine which threads in the WPM are the threads that I programmatically created. Any ideas on how to determine this?
    Thanks.
    Rhodie

    Hi Dmirty ,
    To handle large asynchronous message   in queues you can use  message packaging where multiple message are processed in one package . to make it applicable you have to perform these simple steps
    1. go to SXMB_ADM add one RUNTIME parameter PACKAGING and value 1
    2 GO TO transaction SXMS_BCONF set delay time 0 message count 100 messages and package size 1000 KB
    with these setting your improvement will increase .secondly also put  IN SXMB_ADM monitor category parameter QRFC_RESTART_ALLOWED TO 1
    this will automatically start your queue . Only thing you have to take care if you enable packaging them don't keep too many parallel queue i.e EO_INBOUND_PARALLEL and EO_OUTBOUND_PARALLEL should be less than 20
    Regards,
    Saurabh

  • Java Threads Problem

    Hi, I am trying to write a simple java threads program where in one thread reads a file and another thread writes the data into a second file....
    Here is my code, although i think i am correct, my program still runs in a sequential fashion help help help!!!
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    class MyThread extends Thread{
    private int a;
    private int c;
    FileInputStream in;
    FileOutputStream out;
    public MyThread(int a){
    this.a = a;
    public void run(){
    if(this.a==5)
         try {
         in = new FileInputStream("Britney.txt");
    } catch (FileNotFoundException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
    try {
         while((c=in.read())!=-1)
              a = (char) c;
              System.out.println(a);
    catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
    if(this.a==10)
         try {
              out = new FileOutputStream("romi.txt");
         } catch (FileNotFoundException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
         for(int i = 0;i<50;i++)
              try {
                   System.out.println(c);
                   out.write(c);
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    class MainMyThread{
    public static void main(String args[]){
    MyThread thr1, thr2;
    thr1 = new MyThread(5);
    thr2 = new MyThread(10);
    thr1.start();
    thr2.start();
    }

    Encephalopathic wrote:
    malcolmmc wrote:
    ... Chances of getting any kind of reply except "me too" can be pretty remote. ....there's actually a better chance of getting a reply on a general forum like this one, ....Can't you just post in both the narrow and the general forum, but include links one to the other in each thread? Or is that against the forum rules/etiquette? Most people here are ok with a crosspost IF those links are included.
    I would also ask that the OP designate one of those threads as the real discussion thread and just direct folks there from the other threads, so that we have one coherent discussion. If he does that, there's no problem with trying to reach out to as broad an audience as possible.
    I would figure that if the poster were upfront about what they are doing, folks wouldn't mind, but I could be wrong.I think that's generally the case. As long as the discussion is confined to one thread (and pointed there from the crossposts) or at the very least all the participants can see all the discussions, I think most people don't have a problem with it. It's when we waste our time answering when he's already got the answer elsewhere that's annoying.

  • Java thread not working in windows 7

    I have a Java app that runs just fine on Windows XP. However, on Windows 7 there is a problem related to a job being done via a Java thread.
    Background: The app spawns a separate job via a Java thread and continues on while the spawned job executes. In other words, 2 things happen at once.
    Problem: On Windows 7, when the app spawns the job, Windows sits and waits for the spawned job to complete before it continues on. In other words, 2 things DO NOT happen at once.
    It's as if Java threading does not work in Windows 7. Any input would be greatly appreciated. Thanks.

    l_sleven wrote:
    Thanks for the input, guys. From now on I'll be sure to include a SSCCE.
    I'm beginning to believe this is actually my ignorance of threading in SWT, and XP was more forgiving than 7.
    I would include a SSCCE, but of the 4 different ways I tried to get this to work I wouldn't know which to include since all failed to fix the problem.
    If you want to identify a link to a web page identifying 'best practices' for SWT threading, that would be great. Be aware though that there's a good chance I've already googled the page.
    A programmer smarter than me once said, "The road to best practices is a bumpy ride".[Concurrency in Swing|http://download.oracle.com/javase/tutorial/uiswing/concurrency/index.html]

  • Java thread with high CPU usage

    Hi,
    Running prstat -L -p pid on Solaris produces a list of lwp threads running in that process that are consuming the most CPU. Out of about 7 threads that were associated with kernel threads in pstack output, only 5 of them were mapped to a JVM thread dump. How is it possible to have a Java thread consuming CPU that doesn't show up in a thread dump?
    Thanks,
    J.S.

    And, any idea what this thread is doing?
    Here's pstack output for this missing thread 12:
    ----------------- lwp# 18 / thread# 12 --------------------
    fe0e48b4 __1cHCompileSflatten_alias_type6kMpknHTypePtr__3_ (b6001780, 100360, fe4c8000, b6001780, 100360, 0) + 4d8
    fe0f42ac __1cHCompilePget_alias_index6kMpknHTypePtr__I_ (b6001780, 100360, b6001264, 7e2bb8, 41f4, 7e2bb8) + 8
    fe11131c __1cJStoreNodeFIdeal6MpnIPhaseGVN_pnLPhaseDefUse__pnENode__ (0, 7dd5b4, 5035ec, 7e2bb8, b6001144, b6001264) + 128
    fe0c1224 __1cMPhaseIterGVNNtransform_old6MpnENode__2_ (0, b6001144, 7e2bb8, b6001264, 7e2bb8, b600116c) + 47c
    fe17349c __1cMPhaseIterGVNIoptimize6M_v_ (24, 0, a37700, b6001110, b6001100, 3442f0) + b4
    fe1943b0 __1cOPhaseIdealLoop2t6MrnMPhaseIterGVN_pk0_v_ (b6000ee8, a3772c, 1, 4ff37c, 2000, 269568) + 7cc
    fe1cc89c __1cHCompileIOptimize6M_v_ (b6001780, b60015b8, b6001780, b60015dc, 0, b60013dc) + a0
    fe1cb69c __1cHCompile2t6MpnFciEnv_pnHciScope_pnIciMethod_ill_v_ (91f504, b6001800, db8a24, fe5296b4, b60018a0, b60018b0) + 7bc
    fe1c73f8 __1cKC2CompilerOcompile_method6MpnFciEnv_pnHciScope_pnIciMethod_il_v_ (27b18, b6001af8, db8a24, db8938, ffffffff, 1) + 70
    fe1c79fc __1cNCompileBrokerZinvoke_compiler_on_method6FpnLCompileTask__v_ (db8938, db8a24, fe4eacec, 0, 0, 8d9) + 40c
    fe280964 __1cNCompileBrokerUcompiler_thread_loop6F_v_ (28758, 13a570, fe4c8000, b6001d10, fe4c8000, ffffffff) + 168
    fe216200 __1cKJavaThreadDrun6M_v_ (b5e02000, fe4d3e34, fe4c8000, 1ffd70, 13a570, 1ffd70) + 3d8
    fe213ec8 _start   (fe4c8000, ff325d10, 0, 5, 1, fe401000) + 20
    ff36b734 threadstart (13a570, 0, 0, 0, 0, 0) + 40

  • I want to execute other java thread in the JNI.

    Hi!
    I would like to execute other java native thread concurrently in the Java Native Interface.
    When a Java thread called a native thread to use java native interface, Java thread is blocking for processing native thread.
    So, other java threads don't execute because they are blocking.
    Why do these problems occur at JVM(personal basis profile:CVM)?
    I hope you explain this reason in detail.
    Regard.
    Message was edited by:
    peeppeep

    Cross post
    http://forum.java.sun.com/thread.jspa?threadID=786857&messageID=4471999#4471999

  • How to terminate a java thread from c++ code?

    Hi,
    I made a screensaver which loads a jvm, forks a thread running a java class, wait until user's action(i.e. mouse move/click keyboard input), then terminate the java thread.
    However, I met a problem, How to terminate a running java thread from c++ code?
    Here is my code, but it does not work: (even after the terminate is called, jvm throws an error)
    JNIEnv* env;
    JavaVM* jvm;
    HANDLE hThread; //handle for the startThread
    unsigned __stdcall startThread(void *arg)
         jclass cls;
         jmethodID mainId;
         jint          res;
         int threadNum = (int)arg;
         res = jvm->AttachCurrentThread((void**)&env, NULL);
    cls = env->FindClass( MAIN_CLASS);
         mainId = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
         // setup the parameters to pass to main()
         jstring str;
         jobjectArray args;
         int i=0;
         args = env->NewObjectArray(1, env->FindClass("java/lang/String"), 0); //only one input parameters
         str = env->NewStringUTF("localhost");
         env->SetObjectArrayElement(args, 0, str);
         env->CallStaticVoidMethod(cls, mainId, args); // call main()      
         if (env->ExceptionOccurred()) {
                   env->ExceptionDescribe();
         return TRUE;
    Here is the main method:
    First create the jvm and load the thread. then tries to terminate the thread, but failed here
    switch (msg)
    { case WM_CREATE:
              JavaVMOption options[NUMBEROFOPTIONS];
              JavaVMInitArgs vmargs;     
              jint rc;
              vmargs.version = JNI_VERSION_1_4; /* version 1.4 */
              vmargs.options = options;
              vmargs.nOptions = NUMBEROFOPTIONS;
              vmargs.ignoreUnrecognized = JNI_FALSE;          
              rc=JNI_CreateJavaVM( &jvm, (void **)&env, &vmargs ); /* create JVM */
              /* We pass the thread number as the argument to the invoked thread */
              unsigned int threadId = -1;
              // to initialize a thread-safe C runtime library
              hThread = (HANDLE)_beginthreadex(NULL, 0, &startThread, NULL, 0, &threadId );
    } break;
    case (WM_DESTROY):
              CloseHandle( hThread );
              jvm->DestroyJavaVM(); /* kill JVM */
              Debug("Destroy Java Virtual Machine\n");
    }break;
    Note, after the thread "startThread" runs, it has an infinite loop and will not terminate, until the user clicks to terminate.(I didn't call jvm->DetachCurrentThread();_endthreadex(0); in the "startThread" because the java thread will not terminate by itself)
    Thus, the only way to terminate the thread is to call closehandle(hthread) in the main thread, which may cause jvm to throw an error.
    Do you know how to terminate a java thread safely???
    Thanks a lot

    Assuming that your java thread is in a loop of some kind. Such as
    int i=1; /* I tried using a boolean, I just could not get my C++ env, to change this value. So i decided to use an int */
    run {
    while(i)
    isdfjsdfj
    void seti()
    i=0
    So, B/4, i call destroyVM in my C++ code, i call this seti(). so the loop terminates, therefore my thread finishes executing and ends.
    Hope this helps
    tola.

  • BI Scheduler Java Jobs not working with 11.1.1.6

    Hello,
    I wrote a scheduler java job following the documentation found here
    http://docs.oracle.com/cd/E14571_01/bi.1111/e10541/schedjavajob.htm#CJHCFIID
    It worked fine on OBIEE 11.1.1.3 and 11.1.1.5 but now i made a fresh installation of OBIEE 11.1.1.6.0 and it does't work anymore.
    When i try to run the job from job manager the nqscheduler.exe process starts taking 50% of CPU and nothing happens
    The steps i made after installing OBIEE are:
    1. copy the jar file in ORACLE_HOME\bifoundation\javahost\lib
    2. edit JavaHost configuration file
    <Scheduler>
    <Enabled>True</Enabled> <DefaultUserJarFilePath>E:\<ORACLE_HOME>\bifoundation\javahost\lib</DefaultUserJarFilePath>
    </Scheduler>
    Thanks in Advance,
    Jonni

    thanx this is the solution. With this construct
    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:java="http://xml.apache.org/xalan/java" exclude-result-prefixes="java">
         <xsl:output method="html" indent="yes" encoding="iso-8859-1"/>
         <xsl:template match="/">
         <xsl:variable name="counter" select="java:java.util.Vector.new()"/>
         <xsl:variable name="temp1" select="java:add($counter,'1')"/>
         <xsl:variable name="temp2" select="java:add($counter,'2')"/>
         <xsl:variable name="temp3" select="java:add($counter,'3')"/>
         <xsl:variable name="temp4" select="$temp3"/>
         <xsl:value-of select="java:size($counter)"/>
         <xsl:value-of select="java:toString($counter)"/>
         </xsl:template>
    </xsl:stylesheet>
    at least the '3' is added to the vector.

  • Best option for Asynchronous method invocation? JMS or Pure Java Thread

    Hi,
    We've a swing based Client application which is supposed to run with a server in J2EE environment. Some process like Search etc are very time consuming. So we are going for asynchronous process.
    Now the question is to find a best option for this. Two possible candidates are
    1. JMS
    2. Java Thread.
    Can anybody suggest me which one is the best option in this context?

    Actually my thought was the issues with code maintainability.Maintainability is different issue, it is much related to OOAD and design pattern you might want to choose to avoid coupling (thus high reusability and maintainability - eg: for future enhancement, etc)..
    public interface SearchService {
         public static class DefaultFactory {
                 public SearchService getInstance() {
                          return HttpSearchService.getInstance();
         public void search (String[] keywords, Observer obs);
    public class HttpSearchService implements SearchService {
         public static HttpSearchService getInstance() {
                ... bla bla bla singleton ...
         public void search(final String [] keywords, final Observer obs) {
                     (new Thread() {
                              public void run() {
                                    .. do http request ...
                                    List result =  ... parse http response ...
                                    obs.update(list);
                     }).start();
    SearchService ss = SearchService.DefaultFactory.getInstance();
    ss.search( new String[] { "get", "me", "my" , "dukes" }, myTableModel );
    ...You can, in future, replace the default factory HttpSearchService with something faster, more appropriate SearchService, without changing many codes.
    rgds,
    Alex

Maybe you are looking for

  • Handling password while initial load process

    Dear Experts, This is about password handling in IDM. While doing initial load, I do not want to bring passwords from my target systems (AD/SAP) into IDM. So which password(s) the users will use to login into target systems (AD/SAP) after initial loa

  • Managed Server stuck in starting

    Hi every, thank you for reading. We have a Oracle SOA domain running on WLS 10.3.6. The OS is windows server 2003. Adminserver and soa_server1 are on vmmachine1. proxy server and soa_server2 are on vmmachine2. soa_server1 and soa_server2 are in a clu

  • FIM Synchronization Service - How to provsion a group to another object type

    Hi, i'm new to fim and use just the fim2010 synchronization engine with some rules extensions. I have 2 ActiveDirectories and want to Provision a Group(used as Distribution list) from ActiveDirectory A as a contact object in ActiveDirectory B with th

  • IPhoto crash creating Slideshow

    .... and just about everywhere else!!! 14 crashes in 4 hours during picture import, album creation, slideshow creation, database rebuild ... I have tried rebuilding the database etc. it even crashed twice whilst doing this I have tried creaing a new

  • How do I create a ROM image for emulation?

    Can someone tell me how to create a ROM image from my dying LC III so I can emulate it on my newer mac? I still have a lot of files and software I need to access in the future. OS 9 doesn't work with some of the software on my G4 PowerMac and I will