As written in the title, something in the Timer Interval seems to be off. The timer should take the time from a "DateTimePicker", convert it to seconds & change the Interval to the time set on the DateTimePicker. Afterwards it should post a tweet on twitter, though it doesn't work. It just keeps spamming posts over and over.
private void IntervalChoose_ValueChanged(object sender, EventArgs e) //DateTimePicker
{
postInterval.Interval = (IntervalChoose.Value.Hour * 3600) + (IntervalChoose.Value.Minute * 60) + IntervalChoose.Value.Second;
saveTimerInterval = postInterval.Interval; //saveTimerInterval is set 0 at the beginning
MessageBox.Show("Current Interval in Seconds: " + postInterval.Interval.ToString());
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Start Bot") //Starts program (works)
{
IntervalChoose.Enabled = false;
MessageBox.Show(saveTimerInterval.ToString());
postInterval.Interval = saveTimerInterval; //Sets the interval (once again, safecall)
postInterval.Start(); //starts posting.
button1.Text = "Stop Bot";
}
private void postInterval_Tick(object sender, EventArgs e)
{
var service = new TwitterService("", "", "", ""); //Auth Keys
var twitterStatus = service.SendTweet(new SendTweetOptions() { Status = "Hi" + counter });
if (twitterStatus != null)
{
MessageBox.Show("Your Message:\n\n\"" + "Hi" + counter + "\"\n\n has been successfully tweeted.", "Success!", MessageBoxButtons.OK);
counter++;
}
else
{
//MessageBox.Show("An Error occured while the Bot was running. Please Contact the Developer.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
label2.Text = "Next Post in:\n" + (postInterval.Interval / 3600) + " Hour(s) " + ((postInterval.Interval / 3600) / 60) + " Minute(s) " + (((postInterval.Interval / 3600) / 60) / 60) + " Second(s)";
}
Result:
As seen in the Pictures, the label won't refresh, nor the new set time is being used. It just randomly posted text in a random time. Thanks in advance for the help.
As others mentioned, the Interval
property expects milliseconds, not seconds. In any case, you don't need to make the conversions by hand. A DateTimePicker returns a DateTime value. You can get the time portion of a DateTime as a TimeSpan using the DateTime.TimeOfDay property. The timespan's properties return the various time parts, or the total duration measured in a specific unit. For example, TimeSpan.TotalMilliseconds returns the current time value as milliseconds.
All you need to write is:
postInterval.Interval = (int)IntervalChoose.Value.TimeOfDay.TotalMilliseconds;
That takes care of the invalid interval problem and works only if you want eg to send a message every 10 minutes or every 1 hour.
If you want to send a message at a set time you can't use a System.Windows.Forms.Timer because it doesn't allow you to set a specific start time or start delay. In this case you'd have to use System.Threading.Timer