We help IT Professionals succeed at work.

How to implement a scheduled "Run At" date/time?

seandynan
seandynan asked
on
Medium Priority
258 Views
Last Modified: 2010-04-16
Hi all

I need to implement functionality in my Windows service such that it executes on a given day at a given time. The service has been written in C#.

I need to read a day + time string from a app.config file, e.g.

    <add key="run.at.day.time" value="Thursday, 18:00" />

though I'm open to persuasion about the format of this.

I can't seem to get this to work. The following attempt fails if the day of the week in the app.config file is NOT today(!).

    string[] myFormats = {"dddd, HH:mm"};

    DateTime runAt = DateTime.ParseExact(
            MyConfig.Read("run.at.day.time"),
            myFormats,
            new CultureInfo("en-GB"),
            DateTimeStyles.AllowWhiteSpaces
            );

And is there a way to persuade the DateTime instance that, if the timestamp in the config file is PRIOR to now, that it should assume the timestamp means NEXT WEEK?

Thanks.
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2008

Commented:
if (runat.Subtract(DateTime.Now).TotalDays < 0)
   runat = runat.AddDays(7);

Bob

Author

Commented:
Thanks Bob - that'll probably solve my closing question.

Have you any strategy for implementing my general scheduling task, how to generate a DateTime given just a day and time? At the moment my feeble attempt above is throwing a FormatException if the day isn't today.
CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2008

Commented:
Generally it is acceptable practice to only ask 1 question at a time, in order for these questions to double as a knowledge base, but I am feeling generous this morning.

Can I see your feeble attempt, please?

Bob

Author

Commented:
> but I am feeling generous this morning.

LOL...okay, well my burning question really is, given a string containing a day and a time, how can I get my hands on a DateTime instance that reflects the next occurrence of that day & time?

For example, if today's date was Sunday, 01 Jan 2006 and I offered up "Friday, 13:00" in my config file, how would I generate a DateTime instance that reflected Friday, 06 Jan 2006, 13:00:00 ?


> Can I see your feeble attempt, please?

In a nutshell:

    string[] myFormats = {"dddd, HH:mm"};

    DateTime runAt = DateTime.ParseExact(
            "Friday, 13:00",
            myFormats,
            new CultureInfo("en-GB"),
            DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.AdjustToUniversal
            );

This throws a FormatException ("String was not recognized as a valid DateTime") if the day of the week is NOT today.

Presumably the DateTime constructors expect an actual indication of some kind of date somewhere, and I'm not going to get away with the simple, single-step construction I'm attempting :-(

Thanks.
CERTIFIED EXPERT
Most Valuable Expert 2012
Top Expert 2008
Commented:
Try this method instead:

  public static DateTime TimestampToDate(string timeStamp)
  {

    int pos = timeStamp.IndexOf(",");
    if (pos == -1)
    {
      throw new ArgumentException("Invalid format for timestamp");
    }

    string dayWeek = timeStamp.Substring(0, pos);
    string time = timeStamp.Substring(pos + 1).Trim();
    DayOfWeek weekDay = ((DayOfWeek)(Enum.Parse(typeof(DayOfWeek), dayWeek)));

    pos = time.IndexOf(":");
    if (pos == -1)
    {
      throw new ArgumentException("Invalid time format");
    }

    int hour = Convert.ToInt32(time.Substring(0, pos));
    int minute = Convert.ToInt32(time.Substring(pos + 1));
    DateTime dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, hour, minute, 0);

    while (dt.DayOfWeek != weekDay)
    {
      dt = dt.AddDays(1);
    }

    return dt;

Bob

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
Hey Bob, that works a treat. Many thanks.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.