/** When a task has ended, see if we are finished (no more tasks running). If so, finish. */ @Override public void onTaskEnded(TaskManager manager, ManagedTask task) { int size; // System.out.println(task.getClass().getSimpleName() + "(" + + task.getId() + ") FINISHED // starting"); // Handle the result, and optionally queue another task if (task instanceof SearchThread) handleSearchTaskFinished((SearchThread) task); // Remove the finished task, and terminate if no more. synchronized (mRunningTasks) { mRunningTasks.remove(task); size = mRunningTasks.size(); // for(ManagedTask t: mRunningTasks) { // System.out.println(t.getClass().getSimpleName() + "(" + + t.getId() + ") still running"); // } } if (size == 0) { // Stop listening FIRST...otherwise, if sendResults() calls a listener that starts // a new task, we will stop listening for the new task. TaskManager.getMessageSwitch().removeListener(mTaskManager.getSenderId(), this); System.out.println("Not listening(1)"); // Notify the listeners. sendResults(); } // System.out.println(task.getClass().getSimpleName() + "(" + + task.getId() + ") FINISHED // Exiting"); }
public SimpleOpenTaskDialog(@NotNull final Project project, @NotNull final Task task) { super(project, false); myProject = project; myTask = task; TaskManagerImpl taskManager = (TaskManagerImpl) TaskManager.getManager(myProject); setTitle("Open Task"); myTaskNameLabel.setText(TaskUtil.getTrimmedSummary(task)); TaskManagerImpl manager = (TaskManagerImpl) TaskManager.getManager(project); ControlBinder binder = new ControlBinder(manager.getState()); binder.bindAnnotations(this); binder.reset(); TaskRepository repository = task.getRepository(); if (repository == null || !repository .getRepositoryType() .getPossibleTaskStates() .contains(TaskState.IN_PROGRESS)) { myMarkAsInProgressBox.setVisible(false); } myClearContext.setSelected(taskManager.getState().clearContext); if (!manager.isVcsEnabled()) { myCreateChangelist.setEnabled(false); myCreateChangelist.setSelected(false); } else { myCreateChangelist.setSelected(taskManager.getState().createChangelist); myCreateChangelist.setEnabled(true); } init(); getPreferredFocusedComponent(); }
// Member Methods. public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } // This application uses the model/view/controller // pattern. The controller is responsible for routing // messages between the view (GUI objects) and the // model (back-end objects). // Create the model, view and controller objects. // TaskManager model "runs" the jobs. TaskManager taskManager = new TaskManager(); taskManager.start(); // Create the top-level container and add contents to it. JFrame frame = new JFrame("Task Demo"); taskdemo app = new taskdemo(); app.createComponents(frame.getContentPane()); // Finish up setting up the frame and show it. frame.addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // The window is going away NOW. Just exit. System.exit(0); } }); frame.pack(); frame.setVisible(true); }
/** * Called in UI thread to call the onFinish() method and, if successful, tell the task manager it * has ended. */ private void doFinish() { mFinished = true; if (mManager.isConnected()) { if (onFinish()) { mManager.taskEnded(this); } } }
@Override public void execute() { // TODO Auto-generated method stub if (m_executing) { // 任务处理已经在执行中 return; } else { // Do Nothing } m_executing = true; m_lastStartTime = new Date(); m_lastFinishTime = null; int count = 0; try { count = updateStockInfoYahooFlag(); this.m_lastFinishTime = new Date(); m_TaskManager.saveTaskExecuteLog( m_taskID, m_taskName, m_taskDescription, m_lastStartTime, m_lastFinishTime, true, "完成", "更新[" + count + "]条"); // 保存日志 } catch (Exception ex) { m_lastFinishTime = new Date(); // 保存日志 try { m_TaskManager.saveTaskExecuteLog( m_taskID, m_taskName, m_taskDescription, m_lastStartTime, m_lastFinishTime, false, ex.getMessage(), ex.toString()); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } finally { m_executing = false; } }
public static void regenCluster(final PlotCluster cluster) { if (regenerating.contains(cluster.world + ":" + cluster.getName())) { return; } regenerating.add(cluster.world + ":" + cluster.getName()); final int interval = 1; int i = 0; final Random rand = new Random(); final World world = Bukkit.getWorld(cluster.world); final PlotWorld plotworld = PlotSquared.getPlotWorld(cluster.world); final Location bot = getClusterBottom(cluster); final Location top = getClusterTop(cluster); final int minChunkX = bot.getX() >> 4; final int maxChunkX = (top.getX() >> 4) + 1; final int minChunkZ = bot.getZ() >> 4; final int maxChunkZ = (top.getZ() >> 4) + 1; final AugmentedPopulator populator = getPopulator(cluster); final ArrayList<Chunk> chunks = new ArrayList<>(); TaskManager.runTaskLater( new Runnable() { @Override public void run() { ClusterManager.regenerating.remove(cluster.world + ":" + cluster.getName()); final PlotPlayer owner = UUIDHandler.getPlayer(cluster.owner); if (owner != null) { MainUtil.sendMessage(owner, C.CLEARING_DONE); } } }, (interval * chunks.size()) + 20); // chunks for (int x = minChunkX; x <= maxChunkX; x++) { for (int z = minChunkZ; z <= maxChunkZ; z++) { final Chunk chunk = world.getChunkAt(x, z); chunks.add(chunk); } } for (final Chunk chunk : chunks) { i += interval; TaskManager.runTaskLater( new Runnable() { @Override public void run() { if ((populator == null) || (plotworld.TYPE == 0)) { ChunkLoc loc = new ChunkLoc(chunk.getX(), chunk.getZ()); ChunkManager.manager.regenerateChunk(world.getName(), loc); MainUtil.update(world.getName(), loc); } else { populator.populate(world, rand, chunk); } } }, i); } }
protected void callTaskEnd(final TaskParameter obj) throws Exception { mTaskManager.finished(this); if (null != mCallback) { mCallback.onEndCallback(mType, obj); } }
public static void instantiateAndRegister(TaskManager taskManager) { if (instance == null) { instance = new WaitForTasksTaskHandler(); } taskManager.registerHandler(HANDLER_URI, instance); instance.taskManagerImpl = (TaskManagerQuartzImpl) taskManager; }
public static boolean updateExpired(final String world) { updatingPlots.put(world, true); final long now = System.currentTimeMillis(); if (now > getTimeStamp(world)) { timestamp.put(world, now + 86400000l); TaskManager.runTaskAsync( new Runnable() { @Override public void run() { try { final List<Plot> plots = getOldPlots(world); PS.debug( "$2[&5Expire&dManager$2] $4Found " + plots.size() + " expired plots for " + world + "!"); expiredPlots.put(world, plots); updatingPlots.put(world, false); } catch (Exception e) { e.printStackTrace(); } } }); return true; } else { updatingPlots.put(world, false); return false; } }
@Override public void run() { // TODO Auto-generated method stub if (tm.isFinished()) { this.cancel(); } PrintUtil.debug( "To do Tasks: " + tm.getTodoTasks() + " Done Tasks: " + tm.getDoneTasks() + " Current Threads: " + tm.getTaskThreads()); }
/** * Utility routine to start a task * * @param thread Task to start */ private void startOne(SearchThread thread) { synchronized (mRunningTasks) { mRunningTasks.add(thread); mTaskManager.addTask(thread); // System.out.println(thread.getClass().getSimpleName() + "(" + + thread.getId() + ") // STARTING"); } thread.start(); }
/** * Constructor. * * @param manager Associated task manager * @param taskHandler Object to inform of life0cycle events */ public ManagedTask(TaskManager manager, TaskHandler taskHandler) { // Must be non-null if (manager == null) throw new IllegalArgumentException(); // Save the stuff for mater mManager = manager; mTaskHandler = taskHandler; // Add to my manager mManager.addTask(this); // Create a new Handler. mMessageHandler = new TaskMessageHandler(); // Let the subclass create DB if they need it for now. // mDbHelper = new CatalogueDBAdapter(mContext); }
private void doSearch() { // List for task ends TaskManager.getMessageSwitch().addListener(mTaskManager.getSenderId(), this, false); // System.out.println("Listening"); // We really want to ensure we get the same book from each, so if isbn is not present, do // these in series. boolean tasksStarted = false; mSearchingAsin = false; try { if (mIsbn != null && mIsbn.length() > 0) { if (IsbnUtils.isValid(mIsbn)) { // We have an ISBN, just do the search mWaitingForIsbn = false; tasksStarted = this.startSearches(mSearchFlags); } else { // Assume it's an ASIN, and just search Amazon mSearchingAsin = true; mWaitingForIsbn = false; // mSearchFlags = SEARCH_AMAZON; tasksStarted = startOneSearch(SEARCH_AMAZON); // tasksStarted = this.startSearches(mSearchFlags); } } else { // Run one at a time, startNext() defined the order. mWaitingForIsbn = true; tasksStarted = startNext(); } } finally { if (!tasksStarted) { sendResults(); TaskManager.getMessageSwitch().removeListener(mTaskManager.getSenderId(), this); // System.out.println("Not listening(2)"); } } }
@Override public boolean initPlotMeConverter() { TaskManager.runTaskLaterAsync( new Runnable() { @Override public void run() { if (!(new LikePlotMeConverter("PlotMe").run(new ClassicPlotMeConnector()))) { new LikePlotMeConverter("AthionPlots").run(new ClassicPlotMeConnector()); } } }, 20); return Bukkit.getPluginManager().getPlugin("PlotMe") != null || Bukkit.getPluginManager().getPlugin("AthionPlots") != null; }
/** * Send a message to the player * * @param player the recipient of the message * @param caption the message to send * @return boolean success */ public static boolean sendMessage(PlotPlayer player, C caption, Object... args) { if (caption.s().isEmpty()) { return true; } TaskManager.runTaskAsync( () -> { String m = C.format(caption, args); if (player == null) { PS.log(m); } else { player.sendMessage(m); } }); return true; }
public void run() { while (running) { try { while (!taskManager.threadFlag) { taskManager.threadFlag.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } while ((currentTask = taskManager.getNextTask()) != null) { currentTask.process(threadIndex, threadCount); } } }
@Override public void runEntityTask() { log(C.PREFIX.s() + "KillAllEntities started."); TaskManager.runTaskRepeat( new Runnable() { long ticked = 0l; long error = 0l; @Override public void run() { if (this.ticked > 36_000L) { this.ticked = 0l; if (this.error > 0) { log( C.PREFIX.s() + "KillAllEntities has been running for 6 hours. Errors: " + this.error); } this.error = 0l; } World world; for (final String w : PS.get().getPlotWorlds()) { world = Bukkit.getWorld(w); try { if (world.getLoadedChunks().length < 1) { continue; } for (final Chunk chunk : world.getLoadedChunks()) { final Entity[] entities = chunk.getEntities(); Entity entity; for (int i = entities.length - 1; i >= 0; i--) { if (!((entity = entities[i]) instanceof Player) && (MainUtil.getPlot(BukkitUtil.getLocation(entity)) == null)) { entity.remove(); } } } } catch (final Throwable e) { ++this.error; } finally { ++this.ticked; } } } }, 20); }
private int lookForNumber() { for (int i = start; i < end; i++) { if (numbers[i] == number) { System.out.printf("Task: Number %d found in position %d\n", number, i); manager.cancelTasks(this); return i; } } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } return NOT_FOUND; }
@Override public iTask[] getTasksByUser(UserInfo ui) throws RemoteException, nqException { PreparedStatement stat; try { stat = this.con.prepareStatement( "SELECT `idTask`, `idProject`, `idUserCreatedBy`, `idUserAssignedTo`, `idParentTask`, `TaskStatus`, `Title`," + " `Description`, `Priority`, `CreationDate`, `DeadlineDate`, `MaxHours`, `isSubTask`, `Rating` " + "FROM Tasks WHERE isSubTask = 0 AND idUserAssignedTo = ?"); stat.setInt(1, ui.getID()); return TaskManager.getTasks(stat, this.con); } catch (SQLException ex) { throw new nqException(nqExceptionType.ServerError, "Server error : ".concat(ex.getMessage())); } }
@Override public final ChunkGenerator getDefaultWorldGenerator(final String world, final String id) { WorldEvents.lastWorld = world; if (!PS.get().setupPlotWorld(world, id)) { return null; } HybridGen result = new HybridGen(world); TaskManager.runTaskLater( new Runnable() { @Override public void run() { if (WorldEvents.lastWorld != null && WorldEvents.lastWorld.equals(world)) { WorldEvents.lastWorld = null; } } }, 20); return result; }
private int launchTasks() { int mid = (start + end) / 2; SearchNumberTask t1 = new SearchNumberTask(numbers, start, mid, number, manager); SearchNumberTask t2 = new SearchNumberTask(numbers, mid, end, number, manager); manager.addTask(t1); manager.addTask(t2); // asynchronous t1.fork(); t2.fork(); int returnValue; returnValue = t1.join(); // wait for completion if (returnValue != -1) { return returnValue; } returnValue = t2.join(); // wait for completion return returnValue; }
@Override protected void doOKAction() { TaskManagerImpl taskManager = (TaskManagerImpl) TaskManager.getManager(myProject); taskManager.getState().markAsInProgress = isMarkAsInProgress(); if (taskManager.isVcsEnabled()) { taskManager.getState().createChangelist = myCreateChangelist.isSelected(); } TaskRepository repository = myTask.getRepository(); if (isMarkAsInProgress() && repository != null) { try { repository.setTaskState(myTask, TaskState.IN_PROGRESS); } catch (Exception ex) { Messages.showErrorDialog(myProject, "Could not set state for " + myTask.getId(), "Error"); LOG.warn(ex); } } taskManager.activateTask(myTask, isClearContext(), isCreateChangelist()); if (myTask.getType() == TaskType.EXCEPTION && AnalyzeTaskStacktraceAction.hasTexts(myTask)) { AnalyzeTaskStacktraceAction.analyzeStacktrace(myTask, myProject); } super.doOKAction(); }
private DarkBotMCSpambot(MinecraftBotData data, String owner) throws AuthenticationException, UnsupportedProtocolException { super(data); synchronized (bots) { bots.add(this); } addOwner(owner); addBackend(new ChatBackend(this)); TaskManager taskManager = bot.getTaskManager(); taskManager.registerTask(new FallTask(bot)); taskManager.registerTask(new FollowTask(bot)); taskManager.registerTask(new DefendTask(bot)); taskManager.registerTask(new AttackTask(bot)); taskManager.registerTask(new HostileTask(bot)); taskManager.registerTask(new EatTask(bot)); commandManager.register(new AttackAllCommand(this)); commandManager.register(new AttackCommand(this)); commandManager.register(new CalcCommand(this)); commandManager.register(new ChatDelayCommand(this)); commandManager.register(new DropAllCommand(this)); commandManager.register(new DropCommand(this)); commandManager.register(new DropIdCommand(this)); commandManager.register(new EquipCommand(this)); commandManager.register(new FollowCommand(this)); commandManager.register(new InteractCommand(this)); commandManager.register(new OwnerCommand(this)); commandManager.register(new QuitCommand(this)); commandManager.register(new SayCommand(this)); commandManager.register(new SetWalkCommand(this)); commandManager.register(new SpamCommand(this)); commandManager.register(new StatusCommand(this)); commandManager.register(new StopCommand(this)); commandManager.register(new SwitchCommand(this)); commandManager.register(new ToolCommand(this)); commandManager.register(new WalkCommand(this)); connectionHandler = bot.getConnectionHandler(); Session session = bot.getSession(); System.out.println("[" + session.getUsername() + "] Done! (" + bots.size() + ")"); }
public static void main(String[] args) { TaskManager tm = new TaskManager(); tm.setSearchURL(1000); tm.setNetDeepth(3); tm.setResultToDb(true); tm.setResultToFile(false); tm.setRecords(1000); PrintUtil.debug("设置的搜索容量为 " + tm.getSearchURL()); PrintUtil.debug("设置的搜索深度为 " + tm.getNetDeepth()); PrintUtil.debug( "结果保存在" + (tm.isResultToDb() ? "数据库中" : " ") + (tm.isResultToFile() ? "文件中" : "")); // 保存文件 Calendar c = Calendar.getInstance(); int month = c.get(Calendar.MONTH) + 1; int day = c.get(Calendar.DAY_OF_MONTH); tm.setUrlfilename("url-" + month + "-" + day + ".txt"); // 添加初始网址 Address a = new Address(); String url = "http://www.bilibili.com/"; a.setUrl(url); a.setTitle(url); tm.initAdd(a); tm.start(); // 计时器 Timer t = new Timer(); Counter counter = new Counter(); counter.setTm(tm); t.schedule(counter, 3000, 5000); }
/** * Utility routine to ask the Taskmanager to get a String from a resource ID. * * @param id Resource ID * @return Result */ String getString(int id) { return mManager.getString(id); }
/** * Utility to ask TaskManager to display a toast message * * @param message Message to display */ public void doToast(String message) { mManager.doToast(message); }
/** * Utility to ask the TaskManager to update the ProgressDialog * * @param message Message to display * @param count Counter. 0 if Max not set. */ public void doProgress(String message, int count) { mManager.doProgress(this, message, count); }
public static void main(String[] args) throws IOException { File file = new File("params.xml"); AWSCredentialsProvider credentialsProvider = new ClasspathPropertiesFileCredentialsProvider(); ClientConfiguration conf = null; if (file.exists()) { try { conf = init(file); } catch (Exception e) { e.printStackTrace(); } } String mode = args[0]; String path = args[1] + ":/xyz"; long st = printDate(); String regex1 = "tum"; Pattern p1 = Pattern.compile(regex1, 2); String regex2 = "mokuroku"; Pattern p2 = Pattern.compile(regex2, 2); String regex3 = "cocotile"; Pattern p3 = Pattern.compile(regex3, 2); if (check(p1, mode).booleanValue()) { AmazonDynamoDB Dynamo = new AmazonDynamoDBClient(credentialsProvider, conf); AmazonKinesis kinesis = new AmazonKinesisClient(credentialsProvider, conf); AmazonS3 s3 = new AmazonS3Client(credentialsProvider, conf); TaskManager.tileSearchMain(path, Dynamo, kinesis, s3); } if (check(p2, mode).booleanValue()) { try { DynamoDB.mokuroku(path, conf); } catch (IOException e) { e.printStackTrace(); } } if (check(p3, mode).booleanValue()) { DynamoDB.cocotile(path, conf); } printDate(); //long ed = printDate(); //Calendar c = Calendar.getInstance(); //long sa = ed - st - c.getTimeZone().getRawOffset(); //c.setTimeInMillis(sa); //SimpleDateFormat sdf = new SimpleDateFormat("HH:mm"); //String[] s = sdf.format(c.getTime()).split(":"); //int hour = Integer.parseInt(s[0]); //int minute = Integer.parseInt(s[1]); //System.out.println("total time" + hour + ":" + minute); }
@Override public void requestAbort() { mTaskManager.cancelAllTasks(); }
/** Combine all the data and create a book or display an error. */ private void sendResults() { // This list will be the actual order of the result we apply, based on the // actual results and the default order. ArrayList<Integer> results = new ArrayList<Integer>(); if (mHasIsbn) { // If ISBN was passed, ignore entries with the wrong ISBN, and put entries with no ISBN at the // end ArrayList<Integer> uncertain = new ArrayList<Integer>(); for (int i : mDefaultReliabilityOrder) { if (mSearchResults.containsKey(i)) { Bundle bookData = mSearchResults.get(i); if (bookData.containsKey(CatalogueDBAdapter.KEY_ISBN)) { String isbn = bookData.getString(CatalogueDBAdapter.KEY_ISBN); if (IsbnUtils.matches(mIsbn, isbn)) { results.add(i); } } else { uncertain.add(i); } } } for (Integer i : uncertain) { results.add(i); } // Add the passed ISBN first; avoid overwriting mBookData.putString(CatalogueDBAdapter.KEY_ISBN, mIsbn); } else { // If ISBN was not passed, then just used the default order for (int i : mDefaultReliabilityOrder) results.add(i); } // Merge the data we have. We do this in a fixed order rather than as the threads finish. for (int i : results) accumulateData(i); // If there are thumbnails present, pick the biggest, delete others and rename. Utils.cleanupThumbnails(mBookData); // Try to use/construct authors String authors = null; try { authors = mBookData.getString(CatalogueDBAdapter.KEY_AUTHOR_DETAILS); } catch (Exception e) { } if (authors == null || authors.equals("")) { authors = mAuthor; } if (authors != null && !authors.equals("")) { // Decode the collected author names and convert to an ArrayList ArrayList<Author> aa = Utils.getAuthorUtils().decodeList(authors, '|', false); mBookData.putSerializable(CatalogueDBAdapter.KEY_AUTHOR_ARRAY, aa); } // Try to use/construct title String title = null; try { title = mBookData.getString(CatalogueDBAdapter.KEY_TITLE); } catch (Exception e) { } if (title == null || title.equals("")) title = mTitle; if (title != null && !title.equals("")) { mBookData.putString(CatalogueDBAdapter.KEY_TITLE, title); } // Try to use/construct isbn String isbn = null; try { isbn = mBookData.getString(CatalogueDBAdapter.KEY_ISBN); } catch (Exception e) { } if (isbn == null || isbn.equals("")) isbn = mIsbn; if (isbn != null && !isbn.equals("")) { mBookData.putString(CatalogueDBAdapter.KEY_ISBN, isbn); } // Try to use/construct series String series = null; try { series = mBookData.getString(CatalogueDBAdapter.KEY_SERIES_DETAILS); } catch (Exception e) { } if (series != null && !series.equals("")) { // Decode the collected series names and convert to an ArrayList try { ArrayList<Series> sa = Utils.getSeriesUtils().decodeList(series, '|', false); mBookData.putSerializable(CatalogueDBAdapter.KEY_SERIES_ARRAY, sa); } catch (Exception e) { Logger.logError(e); } } else { // add series to stop crashing mBookData.putSerializable(CatalogueDBAdapter.KEY_SERIES_ARRAY, new ArrayList<Series>()); } // // TODO: this needs to be locale-specific. Currently we probably get good-enough data without // forcing a cleanup. // // Removed 20-Jan-2016 PJW; see Issue 717. // // Cleanup other fields // Utils.doProperCase(mBookData, CatalogueDBAdapter.KEY_TITLE); // Utils.doProperCase(mBookData, CatalogueDBAdapter.KEY_PUBLISHER); // Utils.doProperCase(mBookData, CatalogueDBAdapter.KEY_DATE_PUBLISHED); // Utils.doProperCase(mBookData, CatalogueDBAdapter.KEY_SERIES_NAME); // If book is not found or missing required data, warn the user if (authors == null || authors.length() == 0 || title == null || title.length() == 0) { mTaskManager.doToast(BookCatalogueApp.getResourceString(R.string.book_not_found)); } // Pass the data back sendSearchFinished(); }