Java Code Examples for java.util.TimerTask

The following examples show how to use java.util.TimerTask. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: openjdk-jdk8u   Source File: DelayOverflow.java    License: GNU General Public License v2.0 6 votes vote down vote up
void test(String[] args) throws Throwable {
    for (int how=0; how<4; how++) {
        final CountDownLatch done = new CountDownLatch(1);
        final AtomicInteger count = new AtomicInteger(0);
        final Timer timer = new Timer();
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                checkScheduledExecutionTime(this);
                count.incrementAndGet();
                done.countDown();
            }};

        scheduleNow(timer, task, how);
        done.await();
        equal(count.get(), 1);
        checkScheduledExecutionTime(task);
        if (new java.util.Random().nextBoolean())
            sleep(10);
        check(task.cancel());
        timer.cancel();
        checkScheduledExecutionTime(task);
    }
}
 
Example 2
public void enableStatsEvents(boolean enable, int periodMs) {
    if (enable) {
        try {
            statsTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    executor.execute(new Runnable() {
                        @Override
                        public void run() {
                            getStats();
                        }
                    });
                }
            }, 0, periodMs);
        } catch (Exception e) {
            Log.e(TAG, "Can not schedule statistics timer", e);
        }
    } else {
        statsTimer.cancel();
    }
}
 
Example 3
Source Project: jupyter-kernel-jsr223   Source File: JupyterStreamWriter.java    License: Apache License 2.0 6 votes vote down vote up
private void streaming() {
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            StringBuffer sb = getBuffer();
            synchronized (sb) {
                if (sb.length() > 0) {
                    String S = sb.toString();
                    flush();
                    sb.delete(0, sb.length());
                    ((T_stream) message.msg.content).text = S;
                    message.send();
                }
            }
        }
    }, 250, 250);
}
 
Example 4
Source Project: TencentKona-8   Source File: DelayOverflow.java    License: GNU General Public License v2.0 6 votes vote down vote up
void test(String[] args) throws Throwable {
    for (int how=0; how<4; how++) {
        final CountDownLatch done = new CountDownLatch(1);
        final AtomicInteger count = new AtomicInteger(0);
        final Timer timer = new Timer();
        final TimerTask task = new TimerTask() {
            @Override
            public void run() {
                checkScheduledExecutionTime(this);
                count.incrementAndGet();
                done.countDown();
            }};

        scheduleNow(timer, task, how);
        done.await();
        equal(count.get(), 1);
        checkScheduledExecutionTime(task);
        if (new java.util.Random().nextBoolean())
            sleep(10);
        check(task.cancel());
        timer.cancel();
        checkScheduledExecutionTime(task);
    }
}
 
Example 5
Source Project: werewolf_server   Source File: TimerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
    public  void timeTest(){
        Timer timer = new Timer();
        CountDownLatch countDownLatch = new CountDownLatch(1);
        timer.schedule(new TimerTask(){

            @Override
            public void run() {
                System.out.println("hahh");
                countDownLatch.countDown();
            }
        },  10000);
        try {
//            timer.cancel();  //取消定时器
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
 
Example 6
Source Project: SubServers-2   Source File: Metrics.java    License: Apache License 2.0 6 votes vote down vote up
private void startSubmitting() {
    // We use a timer cause want to be independent from the server tps
    final Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            // Plugin was disabled, e.g. because of a reload (is this even possible in Sponge?)
            if (!Sponge.getPluginManager().isLoaded(plugin.plugin.getId())) {
                timer.cancel();
                return;
            }
            // The data collection (e.g. for custom graphs) is done sync
            // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
            Scheduler scheduler = Sponge.getScheduler();
            Task.Builder taskBuilder = scheduler.createTaskBuilder();
            taskBuilder.execute(() -> submitData()).submit(plugin);
        }
    }, 1000*60*5, 1000*60*30);
    // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
    // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
    // WARNING: Just don't do it!
}
 
Example 7
Source Project: SMP   Source File: MusicService.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onSeekComplete(MediaPlayer mp) {
    // on a 4.1 phone no bug : calling getCurrentPosition now gives the new seeked position
    // on My 2.3.6 phone, the phone seems bugged : calling now getCurrentPosition gives
    // last position. So wait the seekpos goes after the asked seekpos.
    if(seekPosBug != -1) {
        // todo: make it thread safe?
        seekPosNbLoop = seekPosMaxLoop;

        final Timer seekPosTimer = new Timer();
        seekPosTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (seekPosNbLoop-- > 0 || getCurrentPosition() >= seekPosBug) {
                    seekFinished = true;
                    seekPosBug = -1;
                    seekPosTimer.cancel();
                }
            }
        }, 300);
    }
    else {
        seekFinished = true;
    }
    Log.d("MusicService", "onSeekComplete setProgress" + RowSong.secondsToMinutes(getCurrentPosition()));
}
 
Example 8
Source Project: CostFed   Source File: FedSumUpdate.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Update Index after a fixed interval
 * @param lstEndPoints List of SPARQL endpoints
 * @param interval Interval in milliseconds
 * @param outputFile Output location of index
 */
public static void updateIndexAtFixedRate(final List<String> lstEndPoints, long interval, final String outputFile) {
	Timer timer = new Timer();
	timer.scheduleAtFixedRate(new TimerTask() {public void run() { 	 try {
		FedSumGenerator generator = new FedSumGenerator(outputFile);
		long startTime = System.currentTimeMillis();
		generator.generateSummaries(lstEndPoints);
		System.out.println("Index is secessfully updated to "+ outputFile);
		System.out.println("Data Summaries Generation Time (sec): "+ (System.currentTimeMillis()-startTime)/1000);

	} catch (IOException | RepositoryException | MalformedQueryException | QueryEvaluationException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	}  }, 0, interval);

	}
 
Example 9
/**
 * Monitor only deadlocks.
 */
public ThreadWarningSystem() {
  threadCheck.schedule(new TimerTask() {
    @Override
    public void run() {
      long[] ids = mbean.findMonitorDeadlockedThreads();
      if (ids != null && ids.length > 0) {
        for (Long l : ids) {
          if (!deadlockedThreads.contains(l)) {
            deadlockedThreads.add(l);
            ThreadInfo ti = mbean.getThreadInfo(l, MAX_STACK_DEPTH);
            fireDeadlockDetected(ti);
          }
        }
      }
    }
  }, 10, DEADLOCK_CHECK_PERIOD);
}
 
Example 10
Source Project: TrendrrNSQClient   Source File: AbstractNSQClient.java    License: MIT License 6 votes vote down vote up
/**
 * connects, ready to produce.
 */
public synchronized void start() {
    this.connect();

    if (timer != null) {
        timer.cancel();
    }
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            try {
                connect();
            } catch (Throwable t) {
                log.error("Error in periodic `connect` call", t);
            }
        }
    }, lookupPeriod, lookupPeriod);
}
 
Example 11
Source Project: sample-videoRTC   Source File: PeerConnectionClient.java    License: Apache License 2.0 6 votes vote down vote up
public void enableStatsEvents(boolean enable, int periodMs) {
  if (enable) {
    try {
      statsTimer.schedule(new TimerTask() {
        @Override
        public void run() {
          executor.execute(new Runnable() {
            @Override
            public void run() {
              getStats();
            }
          });
        }
      }, 0, periodMs);
    } catch (Exception e) {
      Log.e(TAG, "Can not schedule statistics timer", e);
    }
  } else {
    statsTimer.cancel();
  }
}
 
Example 12
Source Project: jdk8u_jdk   Source File: DelayOverflow.java    License: GNU General Public License v2.0 6 votes vote down vote up
void scheduleNow(Timer timer, TimerTask task, int how) {
    switch (how) {
        case 0 :
            timer.schedule(task, new Date(), Long.MAX_VALUE);
            break;
        case 1:
            timer.schedule(task, 0L, Long.MAX_VALUE);
            break;
        case 2:
            timer.scheduleAtFixedRate(task, new Date(), Long.MAX_VALUE);
            break;
        case 3:
            timer.scheduleAtFixedRate(task, 0L, Long.MAX_VALUE);
            break;
        default:
            fail(String.valueOf(how));
    }
}
 
Example 13
public TimeSizeRestrictedInputStream(InputStream is,
        long timeoutMs, Action timeoutAction,
        long readLimitBytes, Action readLimitAction,
        TransformerDebug transformerDebug)
{
    this.is = useBufferedInputStream ? new BufferedInputStream(is) : is;
    this.timeoutMs = timeoutMs;
    this.timeoutAction = timeoutAction;
    this.readLimitBytes = readLimitBytes;
    this.readLimitAction = readLimitAction;
    this.transformerDebug = transformerDebug;
    
    if (timeoutMs > 0)
    {
        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                timeoutFlag.set(true);
            }
        
        }, timeoutMs);
    }
}
 
Example 14
Source Project: helloiot   Source File: ManagerTime.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void connect() {
    
    disconnect();
    
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        private long lastepochsecond = clock.instant().getEpochSecond();
        @Override
        public void run() {
            long epochsecond = clock.instant().getEpochSecond();
            while (epochsecond - lastepochsecond > 0L) {
                lastepochsecond += 1L;
                byte[] payload = Long.toString(lastepochsecond).getBytes(StandardCharsets.UTF_8);
                consumer.accept(new EventMessage("current", payload));
            }
        }
    }, 0L, 100L);
    
}
 
Example 15
Source Project: SmartOrnament   Source File: SplashActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    // 设置全屏
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_splash);
    //设置定时器,欢迎界面呈现2秒后跳转进入主界面
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    },2000);
}
 
Example 16
Source Project: openjdk-jdk8u   Source File: CrashXCheckJni.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String []s)
{
    final Dialog fd = new Dialog(new Frame(), true);
    Timer t = new Timer();
    t.schedule(new TimerTask() {

        public void run() {
            System.out.println("RUNNING TASK");
            fd.setVisible(false);
            fd.dispose();
            System.out.println("FINISHING TASK");
        }
    }, 3000L);

    fd.setVisible(true);
    t.cancel();
    Util.waitForIdle(null);

    AbstractTest.pass();
}
 
Example 17
Source Project: WeCross   Source File: Chain.java    License: Apache License 2.0 6 votes vote down vote up
public void start() {
    if (!running.get()) {
        running.set(true);

        blockSyncThread =
                new Thread(
                        new Runnable() {
                            @Override
                            public void run() {
                                mainLoop();
                            }
                        });
        blockSyncThread.start();
        logger.trace("Block header sync thread started");

        mainLoopTimer.schedule(
                new TimerTask() {
                    @Override
                    public void run() {
                        noteMainLoop();
                    }
                },
                mainLoopInterval,
                mainLoopInterval);
    }
}
 
Example 18
Source Project: search-spring-boot-starter   Source File: IndexAdmin.java    License: Apache License 2.0 6 votes vote down vote up
@PostConstruct
private void init() {
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            try {// 异步定时更新索引结构
                for (Map.Entry<String, IndexHelper> entry : CACHE.entrySet()) {
                    String[] keyVal = entry.getKey().split(":");
                    String index = keyVal[0];
                    String type = keyVal[1];
                    String mapping = loadIndexStruct(index, type);
                    register(index, type, mapping);
                }
            } catch (Exception e) {
                LOGGER.error("refresh.index.ERROR:" + e.getMessage());
            }
        }
    }, 10000, 5000);
}
 
Example 19
Source Project: NeuralNetworkAPI   Source File: Metrics.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Starts the Scheduler which submits our data every 30 minutes.
 */
private void startSubmitting() {
    final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            if (!plugin.isEnabled()) { // Plugin was disabled
                timer.cancel();
                return;
            }
            // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
            // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
            Bukkit.getScheduler().runTask(plugin, new Runnable() {
                @Override
                public void run() {
                    submitData();
                }
            });
        }
    }, 1000*60*5, 1000*60*30);
    // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
    // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
    // WARNING: Just don't do it!
}
 
Example 20
Source Project: JieCaoVideoPlayer-develop   Source File: JCVideoPlayer.java    License: MIT License 6 votes vote down vote up
protected void startProgressTimer() {
    cancelProgressTimer();
    UPDATE_PROGRESS_TIMER = new Timer();
    UPDATE_PROGRESS_TIMER.schedule(new TimerTask() {
        @Override
        public void run() {
            if (getContext() != null && getContext() instanceof Activity) {
                ((Activity) getContext()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mCurrentState == CURRENT_STATE_PLAYING || mCurrentState == CURRENT_STATE_PAUSE) {
                            setTextAndProgress(0);
                        }
                    }
                });
            }
        }
    }, 0, 300);
}
 
Example 21
Source Project: Skript   Source File: Metrics.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
  * Starts the Scheduler which submits our data every 30 minutes.
  */
 private void startSubmitting() {
     final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
     timer.scheduleAtFixedRate(new TimerTask() {
         @SuppressWarnings("synthetic-access")
@Override
         public void run() {
             if (!plugin.isEnabled()) { // Plugin was disabled
                 timer.cancel();
                 return;
             }
             // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
             // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
             Bukkit.getScheduler().runTask(plugin, new Runnable() {
                 @Override
                 public void run() {
                     submitData();
                 }
             });
         }
     }, 1000*60*5, 1000*60*30);
     // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
     // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
     // WARNING: Just don't do it!
 }
 
Example 22
private void reschedule() {
  if (myUrl == null || myUrl.getHost() == null || myUrl.getHost().length() == 0) {
    onFetchComplete(null);
    return;
  }
  myFetchedFile = null;
  onFetchComplete(null);
  isFetching = true;
  myTimer.schedule(new TimerTask() {
    final URL myUrlAtStart = myUrl;

    @Override
    public void run() {
      synchronized (myTimer) {
        if (!myUrlAtStart.equals(myUrl)) {
          reschedule();
        } else {
          fetch();
        }
      }
    }
  }, 3000);
}
 
Example 23
Source Project: j2objc   Source File: TimerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testTaskNotCancelledWhenTimerCancelled() throws Exception {
    final int timeSleeping = 200;
    Timer t = new Timer();
    final AtomicLong counter = new AtomicLong();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            try {
                counter.incrementAndGet();
                Thread.sleep(timeSleeping);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
        }
    };
    t.scheduleAtFixedRate(task, 1 /* delay */, 100 /* rate */);
    Thread.sleep(1000);
    t.cancel();
    // Returns true as the task wasn't cancelled before.
    assertTrue(task.cancel());
}
 
Example 24
Source Project: cxf   Source File: RedeliveryQueueImpl.java    License: Apache License 2.0 6 votes vote down vote up
protected final synchronized void schedule() {
    if (null == manager.getTimer()) {
        return;
    }
    class RedeliverTask extends TimerTask {
        RedeliverCandidate candidate;

        RedeliverTask(RedeliverCandidate c) {
            candidate = c;
        }

        @Override
        public void run() {
            if (!candidate.isPending()) {
                candidate.initiate();
            }
        }
    }
    nextTask = new RedeliverTask(this);
    try {
        manager.getTimer().schedule(nextTask, next);
    } catch (IllegalStateException ex) {
        LOG.log(Level.WARNING, "SCHEDULE_RESEND_FAILED_MSG", ex);
    }
}
 
Example 25
Source Project: metron   Source File: SourceHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void initialize() throws IOException {
  LOG.debug("Initializing Source Handler");
  this.fs = FileSystem.get(new Configuration());
  this.currentFile = createOutputFile();
  LOG.debug("Source Handler initialized with starting file: {}", currentFile);
  if(this.rotationPolicy instanceof TimedRotationPolicy){
    long interval = ((TimedRotationPolicy)this.rotationPolicy).getInterval();
    this.rotationTimer = new Timer(true);
    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        try {
          LOG.debug("Rotating output file from TimerTask");
          rotateOutputFile();
        } catch(IOException e){
          LOG.warn("IOException during scheduled file rotation.", e);
        }
      }
    };
    this.rotationTimer.scheduleAtFixedRate(task, interval, interval);
  }
}
 
Example 26
Source Project: big-c   Source File: ContainerMetrics.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized void scheduleTimerTaskIfRequired() {
  if (flushPeriodMs > 0) {
    // Lazily initialize timer
    if (timer == null) {
      this.timer = new Timer("Metrics flush checker", true);
    }
    TimerTask timerTask = new TimerTask() {
      @Override
      public void run() {
        synchronized (ContainerMetrics.this) {
          if (!finished) {
            flushOnPeriod = true;
          }
        }
      }
    };
    timer.schedule(timerTask, flushPeriodMs);
  }
}
 
Example 27
Source Project: bitseal   Source File: ViewErrorsActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected void onResume() 
{
	super.onResume();
	
	// Check for new log lines regularly and update the ListView if any are found
       refreshListTask = new TimerTask()
    {
        @Override
        public void run() 
        {
            runOnUiThread(new Runnable()
            {
                public void run() 
                {
                	if (checkForNewLines())
                	{
                		updateListView();
                	}
                }
            });
        }
    };
    new Timer().schedule(refreshListTask, 0, UPDATE_FREQUENCY_MILLISECONDS);
}
 
Example 28
Source Project: RipplePower   Source File: AbstractWebSocket.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Start the connection lost timer
 */
protected void startConnectionLostTimer() {
    if (this.connectionLostTimeout <= 0) {
        if (WebSocketImpl.DEBUG)
            System.out.println("Connection lost timer deactivated");
        return;
    }
    if (WebSocketImpl.DEBUG)
        System.out.println("Connection lost timer started");
    cancelConnectionLostTimer();
    connectionLostTimer = new Timer();
    connectionLostTimerTask = new TimerTask() {
        @Override
        public void run() {
            Collection<WebSocket> con = connections();
            synchronized ( con ) {
                long current = (System.currentTimeMillis()-(connectionLostTimeout * 1500));
                for( WebSocket conn : con ) {
                    if (conn instanceof WebSocketImpl) {
                        if( ((WebSocketImpl)conn).getLastPong() < current ) {
                            if (WebSocketImpl.DEBUG)
                                System.out.println("Closing connection due to no pong received: " + conn.toString());
                            conn.close( CloseFrame.ABNORMAL_CLOSE );
                        } else {
                            conn.sendPing();
                        }
                    }
                }
            }
        }
    };
    connectionLostTimer.scheduleAtFixedRate( connectionLostTimerTask,connectionLostTimeout * 1000, connectionLostTimeout * 1000 );
}
 
Example 29
Source Project: DevToolBox   Source File: Loading.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public void startMainApp(Stage ms) {
    try {
        long time = System.currentTimeMillis();
        Stage stage = new Stage();
        stage.setTitle(Undecorator.LOC.getString("AppName") + " " + Undecorator.LOC.getString("Version") + " 版本号:" + Undecorator.LOC.getString("VersionCode"));
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"));
        Region root = (Region) fxmlLoader.load();
        final UndecoratorScene undecoratorScene = new UndecoratorScene(stage, root);
        stage.setOnCloseRequest((WindowEvent we) -> {
            we.consume();
            undecoratorScene.setFadeOutTransition();
        });
        undecoratorScene.getStylesheets().add("/styles/main.css");
        stage.setScene(undecoratorScene);
        stage.toFront();
        stage.getIcons().add(new Image(getClass().getResourceAsStream("/skin/icon.png")));
        stage.setOnShown((event) -> {
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    Platform.runLater(() -> {
                        ms.close();
                    });
                }
            }, 1000);
        });
        stage.show();
        ApplicationStageManager.putStageAndController(ApplicationStageManager.StateAndController.MAIN, stage, fxmlLoader.getController());
        LOGGER.info("主页面加载耗时:" + (System.currentTimeMillis() - time) + "毫秒");
    } catch (IOException ex) {
        LOGGER.error("启动主程序异常", ex);
    }
}
 
Example 30
Source Project: xDrip   Source File: G5CollectionService.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void setupBluetooth() {

        getTransmitterDetails();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            //First time using the app or bluetooth was turned off?
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            Timer single_timer = new Timer();
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (mBluetoothAdapter != null) mBluetoothAdapter.enable();
                }
            }, 1000);
            single_timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    setupBluetooth();
                }
            }, 10000);
        } else {
            if (Build.VERSION.SDK_INT >= 21) {
                mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
                settings = new ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                        .build();
                filters = new ArrayList<>();
                //Only look for CGM.
                //filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(BluetoothServices.Advertisement)).build());
                String transmitterIdLastTwo = Extensions.lastTwoCharactersOfString(defaultTransmitter.transmitterId);
                filters.add(new ScanFilter.Builder().setDeviceName("Dexcom" + transmitterIdLastTwo).build());
            }

            // unbond here to avoid clashes when we are mid-connection
            if (alwaysUnbond()) {
                forgetDevice();
            }
            JoH.ratelimit("G5-timeout",0);//re-init to ensure onStartCommand always executes cycleScan
            cycleScan(0);
        }
    }