Придерживаясь таймера, я бы предложил что-то вроде этого:
private static System.Timers.Timer myTimer = null;
private static readonly syncObj = new object();
public static bool Execute( bool runTimer )
{
if(runTimer)
{
lock(syncObj) // myTimer access shall be thread safe
{
if(myTimer != null) return false;
// Timer is not active => activate
myTimer = new System.Timers.Timer();
myTimer.AutoReset = false; // 1-Time trigger!!
myTimer.Elapsed += AddOnTimer;
myTimer.Interval = TimeSpan.FromSeconds(30).TotalMilliseconds; // Interval is in ms!
myTimer.Enabled = true;
}
}
else
{
lock(syncObj)
{
if( myTimer == null ) return false;
myTimer.Enabled = false;
myTimer.Dispose();
myTimer = null;
}
}
return true;
}
private static void AddOnTimer(object sender, ElapsedEventArgs e)
{
AddObjToDB();
lock( syncObj )
{
if( myTimer == null ) return; // myTimer has been canceled, meanwhile
myTimer.Elapsed -= AddOnTimer; // Instead of Add, next time
myTimer.Elapsed += RemoveOnTimer; // execute Remove
myTimer.Interval = TimeSpan.FromSeconds(5).TotalMilliseconds;
myTimer.Enabled = true;
}
}
private static void RemoveOnTimer(object sender, ElapsedEventArgs e)
{
RemoveObjFromDB();
lock( syncObj )
{
if( myTimer == null ) return; // myTimer has been canceled
myTimer.Elapsed -= RemoveOnTimer; // Instead of Remove, next time
myTimer.Elapsed += AddOnTimer; // execute Add
myTimer.Interval = TimeSpan.FromSeconds(30).TotalMilliseconds;
myTimer.Enabled = true;
}
}
Asyn c подход:
public static async Task Execute( CancellationToken cancel )
{
while( !cancel.IsCancellationRequested )
{
await Task.Delay(TimeSpan.FromSeconds(30), cancel);
await AddObjToDBAsync(cancel);
await Task.Delay(TimeSpan.FromSeconds(5), cancel);
await RemoveFromDBAsync(cancel);
}
}
private static async Task AddObjToDBAsync( CancellationToken cancel )
{
if( !cancel.IsCancellationRequested )
{
await YourDataLayer.AddAsync( someObj ); // <= I made this up, of course. "Async all the way" is recommended.
}
}
private static async Task RemoveObjFromDBAsync( CancellationToken cancel )
{
if( !cancel.IsCancellationRequested )
{
await YourDataLayer.RemoveAsync( someObj );
}
}
* (Я только что видел, Jeroen уже опубликовал asyn c подход. Я все равно оставлю это здесь.)