Please tell me if I am wrong but I think that you don't want to cancel the runnable inside the for loop.
That will stop the execution at that time, but I assume that it won't prevent it to be executed again and again because it is scheduled indefinitely. So my approach would be to unschedule it rather than terminate it inside the loop.
With this approach, I think you can do something like this, even tho it is a bit tricky:
//We use atomicInteger because the Runnable will be in other thread
AtomicInteger currentIteration = new AtomicInteger(0);
int maxAttempts = 100;
Map<String, Integer> idToProcessIdMap = new HashMap<>();
final String customProcessId = UUID.randomUUID().toString();
Consumer<String> endProcessConsumer = ((generatedId) -> {
int processId = idToProcessIdMap.get(generatedId);
Bukkit.getScheduler().cancelTask(processId);
});
int taskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(main, new Runnable() {
public void run() {
Random rand = new Random();
int rnum = rand.nextInt(main.allowed.size()) + 1;
e.getPlayer().getInventory().addItem(main.allowed.get(rnum));
for(int i = 0; i >= main.getConfig().getInt("SpawnerCase.HowManySpawners"); i++) {
// Something here.
}
int currentIt = currentIteration.incrementAndGet();
if(currentIt > maxAttempts){
endProcessConsumer.accept(customProcessId);
}
}
}, 0L, 0L);
idToProcessIdMap.put(customProcessId, taskId);
Edit: Simplified version
AtomicInteger currentIteration = new AtomicInteger(0);
int maxAttempts = 100;
AtomicInteger processId = new AtomicInteger();
int taskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(main, new Runnable() {
public void run() {
Random rand = new Random();
int rnum = rand.nextInt(main.allowed.size()) + 1;
e.getPlayer().getInventory().addItem(main.allowed.get(rnum));
for(int i = 0; i >= main.getConfig().getInt("SpawnerCase.HowManySpawners"); i++) {
// Something here.
}
int currentIt = currentIteration.incrementAndGet();
if(currentIt > maxAttempts){
Bukkit.getScheduler().cancelTask(processId.get());
}
}
}, 0L, 0L);
processId.set(taskId);
What I do in the code is first to create a variable to identify in which iteration we are.
Then I create a custom identifier for the process you are running and link it with the real process Id in a HashMap. We need to do this because when we run the process, we still don't know which is its id and therefore we won't be able to stop it directly
Also, I create a consumer which I can call inside the process when we reach the max execution times in order to unschedule itself.