0

I have a quartz.net scheduled job. Everytime it runs, i need to update a text file the datetime the job last ran. This file will always have only one line ie. the date the job last ran. What is the best way to write this one line text file thread safe?

I amusing the following code:

private static object locker = new Object();

public void WriteToFile(StringBuilder text)
{
    lock (locker)
    {
        using (FileStream file = new FileStream(Filepath, FileMode.Append, FileAccess.Write, FileShare.Read))
        using (StreamWriter writer = new StreamWriter(file, Encoding.Unicode))
        {
            writer.Write(text.ToString());
        }
    }

}

Thanks

leppie
  • 115,091
  • 17
  • 196
  • 297
Mukil Deepthi
  • 6,072
  • 13
  • 71
  • 156

1 Answers1

1

The best way here is to use a queue; there will be no chance of conflict. For example you can use a BlockingCollection (check this).

First, you need to attach a JobListner to get notified every time a job completes:

public class MyJobListener : JobListenerSupport
{

    BlockingQueue<DateTime> _queue;

    public override string Name
    {
        get { return "AllJobListener"; }
    }

    public override void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException)
    {
        if (jobException == null)
        {
            // do whatever you want
        }
        else
        {
            _queue.Add(DateTime.UtcNow);
        }

        base.JobWasExecuted(context, jobException);
    }
}

where _queue is an instance of a BlockingQueue<DateTime> (you can inject it, or point to a static queue defined somewhere else in the service).

Then you need a a simple timer (defined in the service too) like this:

        Timer t = new Timer(callback =>
        {
            foreach (var msg in _queue.GetConsumingEnumerable())
            {
                File.AppendAllText(msg.Filepath, msg.Text);
            }
        }, null, 0, (long)TimeSpan.FromSeconds(1).TotalMilliseconds);

Obviously you need to use the right period based on you needs, this is just an example.

I suggest you to check this answer for more details on how to write thead-safe.

Luca Ghersi
  • 3,261
  • 18
  • 32