Commit 6d907c58 by pye52

增加某类指令存在未完成状态时不重复插入多条的机制(例如更新操作避免同时执行多次)

parent 347211e1
......@@ -17,8 +17,7 @@ public class CommandHelper {
private static final String CONFIG_LOG = "CONFIG_LOG";
// 设备指令白名单
private static final Set<String> COMMAND_WHITELIST = new HashSet<String>()
{
private static final Set<String> COMMAND_WHITELIST = new HashSet<String>() {
{
add(LOG_UPLOAD);
add(APP_UPDATE);
......@@ -35,10 +34,25 @@ public class CommandHelper {
return command.getAction().equals(CONFIG_LOG);
}
/**
* 根据action检查是否为指令类型
*/
public static boolean isCommand(String action) {
return COMMAND_WHITELIST.contains(action);
}
/**
* 该条指令是否在数据库中只能存在一条"未完成"状态的数据 <br/>
*
* @param command 指令
* @return <br/>
* true => 数据库已有"未完成"状态的该类指令,不应该重复插入 <br/>
* false => 数据库中该类指令都"已完成"或没有该类指令,可插入新的指令 <br/>
*/
public static boolean oneAtTime(Command command) {
return command.getAction().equals(APP_UPDATE);
}
public static OneTimeWorkRequest createWorker(Gson gson, Command command, String deviceSN) {
OneTimeWorkRequest worker = null;
Class<? extends ListenableWorker> workerClass = null;
......
......@@ -17,6 +17,10 @@ public interface CommandDao {
@Query("select * from command where finish == 0 order by id asc")
LiveData<List<Command>> queryUndoneCommand();
// 根据action搜索未完成的指令数
@Query("select count(*) from command where finish == 0 and `action` == :action")
int queryUndoneCommandCountByAction(String action);
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insertCommand(Command command);
......
......@@ -18,6 +18,10 @@ public class CommandRepository {
return dao.queryUndoneCommand();
}
public int queryUndoneCommandCountByAction(String action) {
return dao.queryUndoneCommandCountByAction(action);
}
public long insertCommand(Command command) {
return dao.insertCommand(command);
}
......
......@@ -114,6 +114,14 @@ public class CommandViewModel extends ViewModel {
public void run() {
// 指令插入到数据库,则会触发dataObserver
Command command = new Command(response, action);
// 若为更新指令,则需要检查是否有未完成的,避免同时存在多条更新指令重复执行
if (CommandHelper.oneAtTime(command)) {
int count = commandRepository.queryUndoneCommandCountByAction(action);
if (count > 0) {
LogUtils.d(TAG, "该指令已在数据库中记录并未执行完毕,不再插入重复指令");
return;
}
}
long lastInsertId = commandRepository.insertCommand(command);
if (lastInsertId == -1) {
LogUtils.w(TAG, "指令插入到数据库失败: " + command.toString());
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment