PDA

View Full Version : Is there a Java equivalent to the Javasciprt setInterval() ?



magicgavin
11-25-2008, 04:40 PM
I'm creating a single class java program that needs to constantly run a method.

I know in javascript you can do setInterval("Method",time);
but this obviously does not work in java. Any help would be appreciated.

magicyte
11-25-2008, 10:42 PM
This can be done. First, I will show how to mimic 'setTimeout' which 'setInterval' can evolve from.

Now, I'm no Java wiz. In fact, I don't know ANY Java. However: I know how to make one in C++ (fairly relevant to Java).

This is the code I made. Maybe it will give you an idea:


#include "time.h" // can return time w/ a function

void delay(long unsigned int p) const { // parameter p is # of milliseconds user wishes to pause
clock_t start, end, loop;

start = clock(); // returns time in milliseconds, thus making 'start' the current time
end = (start + p); // end is start + delay number in milliseconds

do {
loop = clock(); // loop will equal current time in milliseconds until loop ends and function returns
} while(loop < end); // continues w/ loop forever until the end is reached
}

Syntax would be:


#include "stdio.h"
#include "conio.h"

int main(void) {
delay(1000);printf("1 second later, this is printed."); // waits 1 second and then prints "1 second later, this is printed."
getch(); // gets keyboard input to proceed with program (it 'pauses' the program)

return 0; // returns and ends program
}

The function listed above is like 'setTimeout' in JavaScript (sort of- read on). In order to make a 'setInterval', we would have to make a loop that won't interfere with the rest of the script. See, since there is a loop in the above script, you can't do anything outside of that function for a while until it stops. I wouldn't know how to do this, but I'm sure it can be done.

What to do:

1. 'Import' or 'include' [header] file into your program that has a function that will fetch the computer's current time in milliseconds (I use "time.h" in C++).

2. Create function relevant to C++ one provided (i.e. replace 'clock()' with Java's version that retrieves time)

3. Compile and execute program

I know you probably won't be able to complete what you wish, but you probably get the idea and understand. If there are any experts out there, please help.

-magicyte

Twey
11-26-2008, 08:30 AM
No, you can't (well, not with anything near the elegance). Javascript is a functional language; Java is not. In Java, it isn't possible to pass functions around as first-class values as one can in Javascript (and should have done with that setInterval() call; passing strings of code around is very bad practice).

The equivalent is something like this:

class MyClass implements Runnable {
public void run() {
while (true) {
Thread.sleep(1000);
// do something
}
}

public static void main(String[] args) {
(new Thread(new MyClass())).start();
}
}magicyte, you really love reinventing the wheel, huh :p C++ may like making you waste time doing everything by hand, but even it provides standard functions for this sort of thing (well, actually, POSIX does). It's called unsigned int sleep(unsigned int seconds), and it's defined in unistd.h. The Windows equivalent (because Microsoft hate following standards) is VOID Sleep(DWORD dwMilliseconds), and can be accessed by including windows.h.

Additionally, your delay() can be written more simply:
void delay(long unsigned int ms)
{
clock_t end = mseconds + clock();
while (end > clock());
}However, none of these are really analogous to the Javascript call, which can be executed asynchronously. Neither Java nor C++ have something like this, since Javascript's only reason for having it is that it has no proper threading support; both Java and C++ do, and therefore the closest equivalent would be using threads. On a POSIX-compliant operating system, this can be done with pthreads, which are a bit clunky but fairly simple:
#include <pthread.h>
#include <unistd.h>

void* thread_proc()
{
while (1) {
sleep(1000);
// do something
}

return NULL;
}

int start_thread()
{
pthread_t th;
return pthread_create(&th, NULL, thread_proc, NULL);
}On Windows, the HANDLE WINAPI CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId) function is used.

magicyte
11-26-2008, 06:46 PM
magicyte, you really love reinventing the wheel, huh :P

Most of the time I do it for my own benefit :D. You see, I don't know everything about coding, so I reinvent the wheel as an excuse for learning, though I probably shouldn't give the code to the public.


On Windows, the HANDLE WINAPI CreateThread(LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId) function is used.

Can you please give an example? Even better: give me a site where examples of windows functions are listed. :D I wouldn't know. Thanks for the clarification.

-magicyte

Twey
11-26-2008, 07:52 PM
I couldn't, no. The Win32 API is a hideous monster, and I stay as far away from it as possible. The signature I pulled off of MSDN (http://msdn.microsoft.com/en-us/library/ms682453(VS.85).aspx).

Reinventing the wheel for educational purposes is one thing, but after you understand it you should use the library functions — and you should use the provided functions anyway in production code (e.g. that offered to those seeking help).

magicyte
11-26-2008, 09:05 PM
I couldn't, no. The Win32 API is a hideous monster, and I stay as far away from it as possible. The signature I pulled off of MSDN.

Okay. *palms faced outward and fingers pointed up* No, really- it's okay.


Reinventing the wheel for educational purposes is one thing, but after you understand it you should use the library functions — and you should use the provided functions anyway in production code (e.g. that offered to those seeking help).

Sure thing. Quick question(s):

1. How would I know the functions libraries provide? I know I can simply look in them, but I don't know exactly what they do. Any suggestions?

2. Would another compiler, non-windows based, provide me with full-fledged header files like 'conio.h' or 'dos.h' (which have functions that don't seem to work on Dev-C++)? You suggest GCC. How would I download it from a mirror site (with directories and such)? I have no idea how to. Here is the site: Texas Mirror Site (http://gcc.releasenotes.org/) There are links in blue. ??? :confused:

Thank you for your help, Twey. I read the below post.

-magicyte

Twey
11-26-2008, 09:24 PM
1. How would I know the functions libraries provide? I know I can simply look in them, but I don't know exactly what they do. Any suggestions?If you find yourself writing functions that seem so generally useful that someone must have implemented them somewhere, chances are someone has. Google. Additionally, the Boost libraries are almost a de-facto standard in C++: acquaint yourself with them.
2. Would another compiler, non-windows based, provide me with full-fledged header files like 'conio.h' or 'dos.h' (which have functions that don't seem to work on Dev-C++)? You suggest GCC. How would I download it from a mirror site (with directories and such)? I have no idea how to. Here is the site: Texas Mirror Site There are links in blue. ??? :confused:No. If you want to use gcc then the easiest way to do it is to install a GNU operating system, which probably means GNU/Linux. Within Windows, you can install Cygwin to get a POSIX-compliant environment and a variety of applications, including gcc. However, you must be aware that you will not get the extra Visual Studio headers by installing gcc. These are only available by installing Visual Studio itself. In fact, if you install gcc within another system, you won't even get the headers you have now: you will instead get their (usually superior) GNU counterparts. There is a version of gcc which targets Windows, and comes with a variety of Windows headers; it is called mingw32, and it is the compiler used by Dev-C++.

jhull
06-23-2009, 09:06 PM
This thread got off topic a little bit. The original question:

Is there a java equivalent to the javascript function setTimeout, setInterval?

The answer is yes. Checkout: ScheduledThreadPoolExecutor

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html

Jesse