如何通过轮询检查智能卡是否存在



我需要检查Java应用程序中是否存在智能卡,以生成类似于智能卡移除的"事件"。

我有一个简单的方法来测试它:

public boolean isCardIn(){};

对此进行民意调查的最佳方式是什么?在这种情况下,我应该使用java.utils.Timer.Timer()还是ExecutorService()


这是我目前的实现:

开始轮询

checkTimer.schedule(new CheckCard(), delay,delay);

这是计时器的执行:

private class CheckCard extends TimerTask{   
    @Override
    public void run() {
        try{
            if(!SmartcardApi.isCardIn(slot)){
                 // fire event
            }
        }catch(Exception e){
        }
    }
}

我想再看看StackOverflow,因为我认为你的问题已经得到了回答:Java定时器与执行程序服务?

我认为一般来说,最好使用更新的API,在这种情况下就是ExecutorService。以下是我的做法:

主要方法

public static void main(String[] args) throws InterruptedException, ExecutionException {
    ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
    SmartCardApi smartCardApi = new SmartCardApi();
    // Polling job.
    Runnable job = new Runnable() {
        @Override
        public void run() {
            System.out.println("Is card in slot? " + smartCardApi.isCardInSlot());
        }
    };
    
    // Schedule the check every second.
    scheduledExecutor.scheduleAtFixedRate(job, 1000, 1000, TimeUnit.MILLISECONDS);
    
    // After 3.5 seconds, insert the card using the API.
    Thread.sleep(3500);
    smartCardApi.insert(1);
    
    // After 4 seconds, eject the card using the API.
    Thread.sleep(4000);
    smartCardApi.eject();
    // Shutdown polling job.
    scheduledExecutor.shutdown();
    
    // Verify card status.
    System.out.println("Program is exiting. Is card still in slot? " + smartCardApi.isCardInSlot());
}

SmartCardApi

package test;
import java.util.concurrent.atomic.AtomicBoolean;
public class SmartCardApi {
    private AtomicBoolean inSlot = new AtomicBoolean(false);
    
    public boolean isCardInSlot() {
        return inSlot.get();
    }
    
    public void insert(int slot) {
        System.out.println("Inserted into " + slot);
        inSlot.set(true);
    }
    public void eject() {
        System.out.println("Ejected card.");
        inSlot.set(false);
    }
}

程序输出

Is card in slot? false
Is card in slot? false
Is card in slot? false
Inserted into 1
Is card in slot? true
Is card in slot? true
Is card in slot? true
Is card in slot? true
Ejected card.
Program is exiting. Is card still in slot? false

在这种情况下,我使用一个简单的Runnable,它可以调用另一个对象来激发它的event。您也可以使用FutureTask而不是此Runnable,但这只是基于您对希望如何触发此事件的偏好。。

相关内容

  • 没有找到相关文章

最新更新