Domanda

I am writing code that will produce a .dat file in Java using RandomAccessFile.

Each file is created an hour long, so after every minute, new data is added, after the hour a new file is created.

For example - each file name is of the date/time format DD-MM-YY-HH. So now it would be 05-11-13-14 and the next one would be 05-11-13-15 and so on.

In the file I am collecting 5 pieces of data and the first piece is of a long value, which is the current timestamp of that time.

What I need is to get the timestamp to print results every minute.

Here is what I have done so far;

public static void main (String [] args) throws FileNotFoundException
{ 
    try
    {
        DateFormat df = new SimpleDateFormat("dd-MM-yy-HH");
        Date date = new Date();
        System.out.println(df.format(date));

        File fileName = new File(df.format(date) + ".dat");
        RandomAccessFile raf = new RandomAccessFile(fileName, "rw");

        for(int i = 0; i < 5; i++)
        {   
            //1383580800000 4/11/2013 4pm
            raf.writeLong(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis());
            raf.writeInt(10);
            raf.writeInt(2);
            raf.write((byte)1);
            raf.writeInt(3);        
        }
        raf.close();
    }
    catch(IOException iOE)
    {
        System.err.println(iOE);
    }
}
È stato utile?

Soluzione

For simply printing the time stamp, all you have to do is date.getTime();. If you just want the epoch value there's absolutely no reason to touch any of the calendar or timezone classes.

If you want to schedule something to run every minute, I would have a look at the ScheduledThreadPoolExecutor class, or simply a Timer.

Altri suggerimenti

You can use Timer and TimerTask for this.

This will execute the run method every 60 seconds.

Start it with: new ScheduleEveryMinute().start()

import java.util.Timer;
import java.util.TimerTask;

public class ScheduleEveryMinute
{
    Timer timer;

    public ScheduleEveryMinute()
    {
        timer = new Timer();
    }

    public void start()
    {
        timer.schedule(new ScheduleTask(), 60000, 60000);
    }

    class ScheduleTask extends TimerTask
    {
        public void run()
        {
             //code to schedule
        }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top