Spinning command line cursor in Java and PHP

Update: I have created an updated article which describes a multithreaded approach in Java Spinning command line cursor in Java

I think I must be really bored this morning, I can’t believe I’m actually blogging this, but it might be useful for someone, who knows.   Anyway, I am currently writing a program that sits and does stuff for a very long time, and I need a way to nicely indicate the program is still running and doing its stuff.   So I have created a little method that prints a spinning cursor on the command line.   The implementation would of course have to be multithreaded; one thread to do stuff, the other to spin the cursor – if there’s time I’ll update it to a more complete solution, but for now here’s the spin implementation:

public class Spin
    public static void main(String[] args) throws InterruptedException
        String[] phases = {"|", "/", "-", "\\"};
        System.out.printf("Spinning... |");
        while (true)
            for (String phase : phases)

And here it is in PHP.

Of course PHP doesn’t support threading so you’d have to call each iteration of the “doing stuff” loop inside the spin loop which would mean you’d get a bit of a jumpy spinning cursor but I think most people could live with that.

This entry was posted in Java, PHP and tagged , , , , , . Bookmark the permalink.

2 Responses to Spinning command line cursor in Java and PHP

  1. goosejan says:

    Hi Nick,

    thanks for this piece of code, it’s really nice to know how to do this in php. :)

    I’ve modified it a bit for using it inside of a foreach loop, maybe this modification may be useful to somebody who needs spinning while walking an array or similar stuff. :)

    $phases = array(“|”, “/”, “-“, “\\”);
    $phase = 0;

    echo “Spinning… |”;

    foreach (EXPRESSION) { // could be while or for or whatever loop

    // Do what you have to do, then:

    if($phase == 4) $phase = 0;
    printf(‘%s%s’, chr(8), $phases[$phase]);

  2. Allie says:

    Wait, I cannot fathom it being so strwightforaard.

Leave a Reply

Your email address will not be published. Required fields are marked *