I am doing backup schedule every day. If any backup file is not created within 24 hours, I want to create new backup file (executing backupdatabase() function).
In addition, I have used a timer, so that every hour it will be checked whether the file is created or not. And after 24 hours it will create a new file (executing backupdatabase() function).
File checking is done by using File.GetcreationTime. Whether the file is created or not.
For that I have done like this…
public partial class BackupForm : Form
{
private static System.Timers.Timer _timer;
private Int32 _hours = 0;
private const Int32 RUN_AT = 10;
private void BackupForm_Load(object sender, EventArgs e)
{
var today = DateTime.Now;
_hours = (24 - (DateTime.Now.Hour + 1)) + RUN_AT;
_timer = new Timer { Interval = _hours * 60 * 60 * 1000 };
_timer.Elapsed += new ElapsedEventHandler(Tick);
_timer.Start();
}
void Tick(object sender, ElapsedEventArgs e)
{
_timer.Stop();
var name = "localhost";
const string path = @"C:\Creation\Name\backupdb\";
var listfiles = Directory.GetFiles(@"C:\Creation\Name\backupdb\", "backup-*.zip").ToList();
var files = listfiles.Select(Path.GetFileName).ToList();
var dt = DateTime.Now;
foreach (var file in files)
{
var creationtime = File.GetCreationTime(file);
var diff = DateTime.Now.Subtract(creationtime);
if (diff.Hours > 24 && diff.Days < 2 && creationtime.Month == dt.Month && creationtime.Year == dt.Year && name == "localhost" && _hours == 24)
{
backupDatabase();
}
else if (_hours != 24)
{
_hours = 24;
_timer.Interval = _hours * 60 * 60 * 1000;
}
}
_timer.Start();
}
}
But it doesn’t work, it does not check the file creation time and even it does not create the file after 24 hours.
How to check the file with creation time along with timer for every one hour and after 24 hours how to create the file?
Any help would be very helpful.
In order to have a method that runs every hour you need to assign a one hour interval to the timer. Timer.Interval is expecting a value in milliseconds so:
This will make the timer “tick” every hour. Inside the Timer_Tick function you should simply check for file dates that are within the last hour:
However, I believe what you are really trying to achieve a solution where you simply create a backup if one has not been created within 24 hours. To achieve this you would use the following:
1) Create a new method called BackupIfNecessary()
2) When your form loads, execute the backup function for the first time by calling BackupIfNecessary in Form_Load (so you don’t wait full 24 hours for the first run)
3) Set a timer interval for 24 hours in Form_Load:
4) Inside of Timer_Tick simply call BackupIfNecessary() which will check if a backup has been created within the last 24 hours, if not it will create one