== ScheduledTimer.cs ==
using System;
using System.Threading;
namespace ScheduledTimer
{
public delegate void stCallBackDelegate();
public class ScheduledTimer
{
private Timer _timer;
public ScheduledTimer() { }
public static TimeSpan GetDueTime(TimeSpan A, TimeSpan B)
{
if (A < B)
{
return B.Subtract(A);
}
else
{
return new TimeSpan(24, 0, 0).Subtract(B.Subtract(A));
}
}
public void SetTime(TimeSpan _time, stCallBackDelegate callback)
{
if (this._timer != null)
{
// Change 매서드 사용 가능.
this._timer = null;
}
TimeSpan Now = DateTime.Now.TimeOfDay;
TimeSpan DueTime = GetDueTime(Now, _time);
this._timer = new Timer(new TimerCallback(delegate(object _callback)
{
((stCallBackDelegate)_callback)();
}), callback, DueTime, new TimeSpan(24, 0, 0));
}
}
}
== Form1.cs ==
using System;
using System.Windows.Forms;
namespace ScheduledTimer
{
public partial class Form1 : Form
{
string DateForm="HH:mm:ss.fff";
bool StartFlag=false ;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//TimeSpan ts = NextSec() ;
//label1.Text += "시작 시간 : " + ts.ToString() ;
}
delegate void ExecMethodCallback() ;
private void ExecMethod()
{
if(textBox1.InvokeRequired)
{
ExecMethodCallback d = new ExecMethodCallback(ExecMethod) ;
this.Invoke(d, new object[] {}) ;
}
else
{
DateTime now = DateTime.Now ;
int cur = (now.Millisecond < 500) ? now.Second : now.Second+1 ;
TimeSpan timeS = new TimeSpan(now.Hour, now.Minute, cur) ;
textBox1.Text += timeS.ToString() + " --- " ;
textBox1.Text += now.ToString(DateForm) +"\r\n" ;
textBox1.SelectixxonStart = textBox1.TextLength;
textBox1.ScrollToCaret();
NextSec() ;
}
}
private TimeSpan NextSec()
{
DateTime now = DateTime.Now ;
int next = (now.Millisecond < 900) ? now.Second+1 : now.Second+2 ;
TimeSpan timeS = new TimeSpan(now.Hour, now.Minute, next) ; // now.Second+1) ;
if(!StartFlag) return timeS ;
ScheduledTimer st = new ScheduledTimer();
//st.SetTime(GetTimeSpan(), ExecMethod); // SetTime(예약시간, 실행메소드)
st.SetTime(timeS, ExecMethod); // SetTime(예약시간, 실행메소드)
return timeS ;
}
private void button1_Click(object sender, EventArgs e)
{
StartFlag = !StartFlag ;
if(StartFlag)
{
TimeSpan ts = NextSec() ;
label1.Text = "시작 시간 : " + ts.ToString() ;
button1.BackColor = System.Drawing.Color.DeepSkyBlue;
}
else
button1.BackColor = System.Drawing.Color.Transparent;
}
}
}