Posts

Showing posts with the label Sleep

Adding A Delay Without Thread.sleep And A While Loop Doing Nothing

Answer : Something like the following should give you the delay you need without holding up the game thread: private final long PERIOD = 1000L; // Adjust to suit timing private long lastTime = System.currentTimeMillis() - PERIOD; public void onTick() {//Called every "Tick" long thisTime = System.currentTimeMillis(); if ((thisTime - lastTime) >= PERIOD) { lastTime = thisTime; if(variable) { //If my variable is true boolean = true; //Setting my boolean to true /** *Doing a bunch of things. **/ //I need a delay for about one second here. boolean = false; //Setting my boolean to false; } } } long start = new Date().getTime(); while(new Date().getTime() - start < 1000L){} is the simplest solution I can think about. Still, the heap might get polluted with a lot of unreferenced Date objects, which, depending on how often you get to create such a pseudo-dela...

Avoiding Busy Waiting In Bash, Without The Sleep Command

Answer : In newer versions of bash (at least v2), builtins may be loaded (via enable -f filename commandname ) at runtime. A number of such loadable builtins is also distributed with the bash sources, and sleep is among them. Availability may differ from OS to OS (and even machine to machine), of course. For example, on openSUSE, these builtins are distributed via the package bash-loadables . Edit: fix package name, add minimum bash version. Creating a lot of subprocesses is a bad thing in an inner loop. Creating one sleep process per second is OK. There's nothing wrong with while ! test_condition; do sleep 1 done If you really want to avoid the external process, you don't need to keep the fifo open. my_tmpdir=$(mktemp -d) trap 'rm -rf "$my_tmpdir"' 0 mkfifo "$my_tmpdir/f" while ! test_condition; do read -t 1 <>"$my_tmpdir/f" done I recently had a need to do this. I came up with the following function that will al...