Home > Java, PHP > Spinning command line cursor in Java and PHP

Spinning command line cursor in Java and PHP

January 29th, 2010 Nick Leave a comment Go to comments

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)
            {
                System.out.printf("\b"+phase);
                Thread.sleep(100);
            }
        }
    }
}

And here it is in PHP.

<?php

    $phases = array("|", "/", "-", "\\");

    printf("Spinning... |");

    while (1)
    {
        foreach ($phases AS $phase)
        {
            printf('%s%s', chr(8), $phase);
            usleep(100000); // Replace this with one iteration of doing stuff
        }
    }

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.

Categories: Java, PHP Tags: , , , , ,
  1. goosejan
    April 6th, 2010 at 11:22 | #1

    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]);
    $phase++;
    }

  1. No trackbacks yet.