我有一个每小时运行一次的cron作业,以便使用API中的小时数据更新本地数据库。我如何加快我的cron作业/数据库更新
数据库按行存储每小时的数据,API返回24个数据点,代表过去24小时。
有时候会丢失一个数据点,所以当我收回数据时,我不能只更新最新的小时 - 我还需要检查以前是否有这个数据,并填写发现空位的任何空位。
一切运行正常工作,但是cron作业至少需要30分钟才能完成每一次,我不知道是否有什么办法让这个运行得更好/更快/更有效?
我的代码执行以下操作:(概要代码简洁!)
// loop through the 24 data points returned
for($i=0; $i<24; $i+=1) {
// check if the data is for today, because the past 24 hours data will include data from yesterday
if ($thisDate == $todaysDate) {
// check if data for this id and this time already exists
$query1 = "SELECT reference FROM mydatabase WHERE ((id='$id') AND (hour='$thisTime'))";
// if it doesnt exist, insert it
if ($datafound==0) {
$query2 = "INSERT INTO mydatabase (id,hour,data_01) VALUES ('$id','$thisTime','$thisData')";
}
}
}
而且有1500点不同的ID,所以它这个1500倍!
有没有什么办法可以加快或优化这段代码,使其运行速度更快,效率更高?
在存储过程中使用select然后条件插入将优化查询执行。 – Abhishek
所以,我假设你的表'mydatabase'的现有大小很大。一种方法是使用适当的主键将所有内容加载到临时表(可能使用'insert ignore'),然后加入到'mydatabase'中并更新一次。您可能能够为临时表使用内存表,这可能会更快。 –